Usually, I will use the :: primitive thus:
SomeVariable"_ :: ] DefaultValue
I'm looking for a way to wrap that ugly SOB. I'm trying to reason it. Normally, it would be with a tacit definition. This, for example:
default =: 13 : 'x"_ :: ] y'
fails miserably. Because, of course, in this context:
SomeVariable default DefaultValue
if SomeVariable doesn't exist, J will throw a valence error.
So, how can you wrap ::?
You can indeed wrap :: but if you want to give it a verb argument, you need to deal with the syntactic issues.
For example, you can use an adverb:
fault=:1 :0
u"_ :: ]
)
Or you could convert the verb you are manipulating into a gerund and pass that in (but that would be ugly, so I do not think you want that).
I use,
ORdef_z_ =: ".#[^:(_1< 4!:0#<#[)
'asd' ORdef 3 NB. asd not assigned, returns right.
3
asd =. 'asd' ORdef 3
asd=.'asd' ORdef 22 NB. will return 3 due to previous assignment
asd
3
Related
If I have a variable my $a = True, then I get this output from the following code:
say «a list of words foo $a bar baz».raku;
# OUTPUT: ("a", "list", "of", "words", "foo", "True", "bar", "baz")
That is, even though the result is a List, the element True is stringified before being included in the list – the list contains "True", not True. Is there any way to avoid that stringification while still using interpolation?
Would there be a way to do so if $a were a class I'd defined (and thus can write the Str method for) rather than a Bool?
(I am aware that I can write the more verbose ("a", "list", "of", "words", "foo", $a, "bar", "baz") or «a list of words foo».Slip, $a, «bar baz».Slip, but I'm asking if there is a way to still use interpolation).
Interpolation is putting a thing into a string.
"a b c $thing d e f"
It does that by first turning the thing itself into a string, and concatenating the rest of the string around it.
Basically the above compiles into this code:
infix:<~>( 「a b c 」, $thing.Str, 「 d e f」 )
« a b c $thing »
Is short for:
Q :double :quotewords « a b c $thing d e f »
That is use the Quoting DSL, turning on :double quote semantics (“”) and turning on :quotewords.
:quotewords is the feature which splits the string into its individual parts.
It happens only after it has been turned into a string.
Imagine that the above compiles into:
Internals::quotewords( infix:<~>( 「 a b c 」, $thing.Str, 「 d e f 」 ) )
There is another way to get what you want, other than using .Slip or prefix |.
flat «a list of words foo», $a, «bar baz»
The whole purpose of the quoting DSL is that it produces a string.
That said :words, :quotewords, and :val all change it so that it returns something other than a single string.
And the idea of them is that they alter the DSL.
So MAYBE you could convince enough people that such a change would be worth it.
Thats a big maybe.
It would potentially break many existing codebases, so you would have an uphill battle to do so.
What happens here has little to do with quoting, and a lot to do with context. As #brad-gilbert has indicated, anything that goes passes through putting ~ in front, which is coercing the variable to a String context.
But that yields an answer to your second question:
Would there be a way to do so if $a were a class I'd defined (and thus can write the Str method for) rather than a Bool?
Theoretically, something like this should work:
class A {
has Bool $.foo;
method Str { $.foo }
};
my $a = A.new( :foo(True) );
say «a b $a».raku
Alas, this returns «No such method 'WORDS_AUTODEREF' for invocant of type 'Bool' so it probably needs a bit of work (or I might have bumped into some bug). So this is, for the time being, and for your precise example, a nanswer. As a matter of fact, only Strs have that method, so I think that for the time being, and unless you bother to create that specialized method for a class, it's difficult to do.
I am trying to creating y shape random float array, and this is my current right now:
input_dim =: 2
hidden_dim =: 16
0 ?#$ ~ (input_dim, hidden_dim)
0.838135 0.96131 0.766721 0.420625 0.640265 0.683779 0.683311 0.427981 0.281479 0.305607 0.385446 0.898389 0.24596 0.452391 0.739534 0.973384
0.914155 0.172582 0.146184 0.624908 0.333564 0.132774 0.475515 0.802788 0.277571 0.146896 0.40596 0.735201 0.943969 0.259493 0.442858 0.374871
It seems like this code returns what I exactly want, so I tried to make a function like below:
rand =: 0 ?#$ ~
but rand (input_dim, hidden_dim) gives me a syntax error...
I think I am missing one very important part, but I am not sure what that is.
Any advice would be grateful!
The only thing missing from your verb is ].
That is:
rand =: 0 ?#$~ ]
rand 2 3
0.891663 0.888594 0.716629
0.9962 0.477721 0.946355
Potentially your confusion arose because you were wanting to create a fork of the form (noun verb verb), however ~ is an adverb and so combines with the verb to its left to create a new verb (in your case ?#$~) so your rand had the form (0 ?#$~) or (noun verb) which J does not recognise - hence the syntax error.
It makes sense to use the combination ?#$ if possible because it is supported by special code and does not create x $ y.
Without the argument, the syntax of 0 ?#$ ~ is ambiguous and the interpreter missclassifies the parenthesization (or, more accurately, the correct parenthesization is not the one you think it is).
The easiest way around this is to define rand as:
rand =: 3 :'0 ?#$ ~ y'
Of course, any other way of removing the syntactic ambiguity will also work:
rand =: [: ? 0 $~ ]
rand =: ?#(0$~])
rand =: ?#(0&($~))
...
I'm sure this is obvious but I'm a little unclear about it. Suppose I wanted to make a function do something like f(x) = 3x+1. Knowing the rule for forks, I expect to see something like this: [: 1&+ 3&* which is not that beautiful to me, but I guess is nicer looking that (1&+) #: (3&*) with the extra parentheses. Instead, if I query with 13: I get this:
13 : '1+3*y'
1 + 3 * ]
Way more beautiful, but I don't understand how it is possible. ] is the identity function, * and + are doing their usual thing, but how are the literals working here? Why is J not attempting to "call" 1 and 3 with arguments as if they are functions? I notice that this continues to do the right thing if I replace any of the constants with [ or ], so I think it is interpreting this as a train of some kind, but I'm not sure.
When J was first described, forks were all verbs (V V V), but then it was decided to let nouns be in the left tine position and return their face value. So (N V V) is seen as a fork as well. In some older code you can see the left tine of the fork show up as a 'verbified' noun such as 1: or 'a'"_ which act as verbs that return their face value when given any argument.
(N V V) configuration is described in the dictionary as "The train N g h (a noun followed by two verbs) is equivalent to N"_ g h ." http://www.jsoftware.com/help/dictionary/dictf.htm
In a Codefights challenge where you have to add two numbers the user kaiochao had a super minimalisic answer
add = (+)
How does it work and has this functionality a own name?
Here's an explicit definition:
add a b = a + b
There is a feature in Haskell that says that we can rewrite a + b as (+) a b, this is due to the fact that operators are functions in Haskell. So we can rewrite:
add a b = (+) a b
But then we're doing nothing extra to the arguments of this function, so we can reduce this function by removing the explicit arguments*. Note that this requires an understanding of how function application in Haskell works:
add = (+)
This is because functions are data in Haskell. This is literally saying that plus and the function of addition are the same thing.
In practice, we can see this by substituting:
add 1 2
= (+) 1 2 -- Since add = (+), this can be read literally.
= 1 + 2 -- This is how operators work in Haskell.
= 3 -- Calculation.
This is known as pointfree style in Haskell.
*As #Benjamin Hodgson mentioned, this is called eta-reduction.
This “functionality” is just variable assignment. It works the same way as writing
three = 3
3 is just a Haskell value, which I can at any point give a new name, refer to it, and get something that's (at least, at runtime) indistinguishable from 3 itself.
The fact that add has a somewhat more complicated type, namely a function type, changes nothing about the way such variable assignments work. I can certainly define
root = sqrt
...and then evaluate root 4 to obtain 2.0 as the result. Or, for any custom function,
foo :: Int -> String
foo n = concat $ replicate n (show n)
bar = foo
GHCi> bar 3
"333"
GHCi> bar 7
"7777777"
All that is really no different from how I can also write
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import math
In [2]: root = math.sqrt
In [3]: root(4)
Out[3]: 2.0
What's a bit more interesting about add is that + is an infix operator (because it consists of non-letter characters). But Haskell allows using such infix operators pretty much just as liberally as any other variables, including that you can define your own. The only thing that's a bit different are the parsing rules. + can not be a standalone syntactic unit but has to be surrounded on each side with with arguments you want to add, or with parentheses. The latter, (+), is really what the plus operator is from the compiler's point of view: the binary function, not yet applied to any arguments. So, when you want to give this operator a new name, you need to write
add = (+)
Incidentally, you could also give it a new operator-name, like
(⊕) = (+)
...that could then be used like 3 ⊕ 4, just as you can with the standard + operator.
Why is the function name repeated in
example:
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
when should I not be repeating function name? what is the meaning of it?
thanks
What you are seeing is pattern match in action.
I will show you another example:
test 1 = "one"
test 2 = "two"
test 3 = "three"
Demo in ghci:
ghci> test 1
"one"
ghci> test 2
"two"
ghci> test 3
"three"
ghci> test 4
"*** Exception: Non-exhaustive patterns in function test
So, when you call any function, the runtime system will try to match
the input with the defined function. So a call to test 3 will
initially check test 1 and since 1 is not equal to 3, it will
move on to the next definition. Again since 2 is not equal to 3,
it will move to the next defintion. In the next definiton since 3 is
equal to 3 it will return "three" String back. When you try to
pattern match something, which doesn't exist at all, the program
throws the exception.
This kind of pattern matching can be transformed to a case statement (and indeed, that's what compilers will normally do!):
lucky' n = case n of
7 -> "LUCKY NUMBER SEVEN!"
x -> "Sorry, you're out of luck, pal!"
Because the x isn't really used, you'd normally write _ -> "Sorry, ..." instead.
Note that this is not2 the same as
lucky'' n = if n==7 then ...
Equality comparison with (==) is in general more expensive1 than pattern matching, and also comes out uglier.
1 Why it's more expensive: suppose we have a big data structure. To determine that they are equal, the program will need to dig through both entire structures, make sure really all branches are equal. However, if you pattern match, you will just compare a small part you're interested in right now.
2 Actually, it is the same in the case, but just because the compiler has a particular trick for pattern matching on numbers: it rewrites it with (==). This is really special for Num types and not true for anything else. (Except if you use the OverloadedStrings extension.)
That definition of lucky uses "pattern matching", and equals (in this case)
lucky :: (Integral a) => a -> String
lucky a = if a == 7
then "LUCKY NUMBER SEVEN!"
else "Sorry, you're out of luck, pal!"
I assume you're looking at learn you a haskell. After that example, it says that
When you call lucky, the patterns will be checked from top to bottom and when it conforms to a pattern, the corresponding function body will be used.
So the first line indicates the type of the function, and later lines are patterns to check. Each line has the function name so the compiler knows you're still talking about the same function.
Think of it this way: When you write the expression lucky (a+b) or whatever, the compiler will attempt to replace lucky (a+b) with the first thing before the = in the function definition that "fits." So if a=3 and b=4, you get this series of replacements:
lucky (a+b) =
lucky (3+4) =
--pattern matching occurs...
lucky 7 =
"LUCKY NUMBER SEVEN!"
This is part of what makes Haskell so easy to reason about in practice; you get a system that works similarly to math.