Shen and curried S-expressions - currying

Are functions in Shen uniadic or variadic? Is (+ 1 2 3) in Shen shorthand for (+ 1 (+ 2 3))? I am curious about currying in Shen, and how it works together with S-expressions.
edit
After I have played around with the REPL, I believe functions are uniadic. I am impressed by the pattern matching, but can not understand how to write a function that behaves as + if I call it with more than two operands.

Functions arent variadic, but some macros are.
(0-) (and true true true)
true
(1-) (macroexpand [and true true true])
[and true [and true true]]
(2-) (macroexpand [+ 1 2 3])
[+ 1 [+ 2 3]]
See defmacro for creating new ones:
http://www.shenlanguage.org/learn-shen/macros.html

Related

How to handle missing in boolean context in Julia?

I'm trying to create a categorical variable based on ranges of values from other (numerical) column. However, the code don't work when I have missings in the numerical column
Here is a replicable example:
using RDatasets;
using DataFrames;
using Pipe;
using FreqTables;
df = dataset("datasets","iris")
#lowercase columns just for convenience
#pipe df |> rename!(_, [lowercase(k) for k in names(df)]);
#without this line, the code works fine
#pipe df |> allowmissing!(_, :sepallength) |> replace!(_.sepallength, 4.9 => missing);
df[:size] = #. ifelse(df[:sepallength]<=4.7, "small", missing)
df[:size] = #. ifelse((df[:sepallength]>4.7) & (df[:sepallength]<=4.9), "avg", df[:size])
df[:size] = #. ifelse((df[:sepallength]>4.9) & (df[:sepallength]<=5), "large", df[:size])
df[:size] = #. ifelse(df[:sepallength]>5, "huge", df[:size])
println(#pipe df |> freqtable(_, :size))
Output:
TypeError: non-boolean (Missing) used in boolean context
I would like to ignore the missing cases in the numerical variable but I cannot just drop de missings because this will drop other important informations in my dataset. Moreover, if I drop just the missings in sepallength the column df[:size] would have a different length than the original dataframe.
Use the coalesce function like this:
julia> x = [1,2,3,missing,5,6,7]
7-element Array{Union{Missing, Int64},1}:
1
2
3
missing
5
6
7
julia> #. ifelse(coalesce(x < 4.7, false), "small", missing)
7-element Array{Union{Missing, String},1}:
"small"
"small"
"small"
missing
missing
missing
missing
As a side note do not write df[:size] (this syntax has been deprecated for over 2 years now and soon it will error) but rather df.size or df."size" to access the column of the data frame (the df."size" is for cases when your column names contain characters like spaces etc., e.g. df."my fancy column!").
I think Bogumil's approach is correct and probably best for most situations, but one other option that I like to use is to define my own comparison operators that can deal with missings by returning false if a missing is encountered. Using the unicode capabilities of Julia makes this quite pleasant in my opinion:
julia> ==ₘ(x, y) = ismissing(x) | ismissing(y) ? false : x == y;
julia> >=ₘ(x, y) = ismissing(x) | ismissing(y) ? false : x >= y;
julia> <=ₘ(x, y) = ismissing(x) | ismissing(y) ? false : x <= y;
julia> <ₘ(x, y) = ismissing(x) | ismissing(y) ? false : x < y;
julia> >ₘ(x, y) = ismissing(x) | ismissing(y) ? false : x > y;
julia> x = rand([missing; 1:10], 50)
julia> x .> 10
50-element Array{Union{Missing, Bool},1}
...
julia> x .>ₘ 10
50-element BitArray{1}
...
There are of course downsides to defining such an elementary operator in your own code, particularly using Unicode as well, in terms of your code being harder for other people to read (and potentially even to display correctly!), so I probably wouldn't advocate for this as the standard approach, or something to be used in library code. I do think though that for explorative work it makes life easier.

macro for pandas column setting in hy

I feel I'm writing functions needlessly for the following operation of setting several derived columns sequentially:
(defn add-cols[d]
(do
(setv (get d "col0") "0")
(setv (get d "col1") (np.where (> 0 (get d "existing-col")) -1 1))
(setv (get d "col2") (* (get d "col1") (get d "existing-col")))
d
))
The above is neither succinct nor easy to follow. I'd appreciate any help with converting this pattern to a macro. I'm a beginner with macros but am thinking of creating something like so :
(pandas-addcols d
`col0 : "0",
`col1 : (np.where ( > 0 `existing-col) -1 1),
`col2 : (* `col1 `existing-col))
Would appreciate any help or guidance on the above. The final form of the macro can obviously be different too. Ultimately the most repetitive bit is the multiple "setv" and "get" calls and maybe there are more elegant a generic ways to remove those calls.
A little syntactic sugar that can help is to use a shorter name for get and remove the need to quote the string literal. Here's a simple version of $ from this library. Also, Hy's setv already lets you provide more than one target–value pair.
(import
[numpy :as np]
[pandas :as pd])
(defmacro $ [obj key]
(import [hy [HyString]])
`(get (. ~obj loc) (, (slice None) ~(HyString key))))
(setv
d (pd.DataFrame (dict :a [-3 1 3] :b [4 5 6]))
($ d col0) 0
($ d col1) (np.where (> 0 ($ d a)) -1 1))

Nested condition word problem on boolean values and inequalities

(This code is written in Dr. Racket) I have to come up with a function which produces true for even numbers less than 4 or true for even numbers greater than 30 and false otherwise. This is my code:
(define (special-number n)
(cond
[(even?) n])
cond [(< n 4) n]
[(> n 30) n]
[else false]))
For some reason, my code isn't working. Some help would be greatly appreciated.
The first condition is incorrect, if the number is even you're returning it immediately. And the second cond isn't working, you forgot to put it inside brackets. The problem is straightforward, we just need to write the statement in code, word by word:
(define (special-number n)
(cond
; true for even numbers less than 4
((and (even? n) (< n 4)) true)
; true for even numbers greater than 30
((and (even? n) (> n 30)) true)
; false otherwise
(else false)))

Raku (née Perl 6) reduce function and reduction metaoperator give different results

my #s=<1 2 3 2 3 4>;
say reduce {$^a < $^b}, #s;
say [<] #s;
# --------
# True
# False
My question is two fold:
Firstly, why does the reduction metaoperator processes the < operator differently? It looks like the reduction metaop is estimatedly using a variable which, at the first change of true to false, retains that change because:
say [\<] #s;
# ----------
# (True True True False False False)
Secondly, I'd like to use this inside the reduce function, too, i.e. introducing some code inside the curly brackets of reduce function so that it gives the same result as the reduction meta operator. How can I do it? Thank you.
Both the meta-operator and reduce take into account the associativity of the operator passed to them; in the case of <, the operator is chaining.
When passing a custom block, reduce cannot see inside of it, and so it falls back to the default of left-associative; it then compares the later values against the boolean returned from the reducer, which numifies to 0 or 1, which is why the result ends up as True in the end.
You can get the semantics you desire by declaring your reduction function as having chaining associativity:
my #s1 =<1 2 3 2 3 4>;
my #s2 =<1 2 3 4>;
sub my-reducer($a, $b) is assoc('chain') {
$a < $b
}
say reduce &my-reducer, #s1; # False
say reduce &my-reducer, #s2; # True

foldl is tail recursive, so how come foldr runs faster than foldl?

I wanted to test foldl vs foldr. From what I've seen you should use foldl over foldr when ever you can due to tail reccursion optimization.
This makes sense. However, after running this test I am confused:
foldr (takes 0.057s when using time command):
a::a -> [a] -> [a]
a x = ([x] ++ )
main = putStrLn(show ( sum (foldr a [] [0.. 100000])))
foldl (takes 0.089s when using time command):
b::[b] -> b -> [b]
b xs = ( ++ xs). (\y->[y])
main = putStrLn(show ( sum (foldl b [] [0.. 100000])))
It's clear that this example is trivial, but I am confused as to why foldr is beating foldl. Shouldn't this be a clear case where foldl wins?
Welcome to the world of lazy evaluation.
When you think about it in terms of strict evaluation, foldl looks "good" and foldr looks "bad" because foldl is tail recursive, but foldr would have to build a tower in the stack so it can process the last item first.
However, lazy evaluation turns the tables. Take, for example, the definition of the map function:
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
This wouldn't be too good if Haskell used strict evaluation, since it would have to compute the tail first, then prepend the item (for all items in the list). The only way to do it efficiently would be to build the elements in reverse, it seems.
However, thanks to Haskell's lazy evaluation, this map function is actually efficient. Lists in Haskell can be thought of as generators, and this map function generates its first item by applying f to the first item of the input list. When it needs a second item, it just does the same thing again (without using extra space).
It turns out that map can be described in terms of foldr:
map f xs = foldr (\x ys -> f x : ys) [] xs
It's hard to tell by looking at it, but lazy evaluation kicks in because foldr can give f its first argument right away:
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
Because the f defined by map can return the first item of the result list using solely the first parameter, the fold can operate lazily in constant space.
Now, lazy evaluation does bite back. For instance, try running sum [1..1000000]. It yields a stack overflow. Why should it? It should just evaluate from left to right, right?
Let's look at how Haskell evaluates it:
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
sum = foldl (+) 0
sum [1..1000000] = foldl (+) 0 [1..1000000]
= foldl (+) ((+) 0 1) [2..1000000]
= foldl (+) ((+) ((+) 0 1) 2) [3..1000000]
= foldl (+) ((+) ((+) ((+) 0 1) 2) 3) [4..1000000]
...
= (+) ((+) ((+) (...) 999999) 1000000)
Haskell is too lazy to perform the additions as it goes. Instead, it ends up with a tower of unevaluated thunks that have to be forced to get a number. The stack overflow occurs during this evaluation, since it has to recurse deeply to evaluate all the thunks.
Fortunately, there is a special function in Data.List called foldl' that operates strictly. foldl' (+) 0 [1..1000000] will not stack overflow. (Note: I tried replacing foldl with foldl' in your test, but it actually made it run slower.)
Upon looking at this problem again, I think all current explanations are somewhat insufficient so I've written a longer explanation.
The difference is in how foldl and foldr apply their reduction function. Looking at the foldr case, we can expand it as
foldr (\x -> [x] ++ ) [] [0..10000]
[0] ++ foldr a [] [1..10000]
[0] ++ ([1] ++ foldr a [] [2..10000])
...
This list is processed by sum, which consumes it as follows:
sum = foldl' (+) 0
foldl' (+) 0 ([0] ++ ([1] ++ ... ++ [10000]))
foldl' (+) 0 (0 : [1] ++ ... ++ [10000]) -- get head of list from '++' definition
foldl' (+) 0 ([1] ++ [2] ++ ... ++ [10000]) -- add accumulator and head of list
foldl' (+) 0 (1 : [2] ++ ... ++ [10000])
foldl' (+) 1 ([2] ++ ... ++ [10000])
...
I've left out the details of the list concatenation, but this is how the reduction proceeds. The important part is that everything gets processed in order to minimize list traversals. The foldr only traverses the list once, the concatenations don't require continuous list traversals, and sum finally consumes the list in one pass. Critically, the head of the list is available from foldr immediately to sum, so sum can begin working immediately and values can be gc'd as they are generated. With fusion frameworks such as vector, even the intermediate lists will likely be fused away.
Contrast this to the foldl function:
b xs = ( ++xs) . (\y->[y])
foldl b [] [0..10000]
foldl b ( [0] ++ [] ) [1..10000]
foldl b ( [1] ++ ([0] ++ []) ) [2..10000]
foldl b ( [2] ++ ([1] ++ ([0] ++ [])) ) [3..10000]
...
Note that now the head of the list isn't available until foldl has finished. This means that the entire list must be constructed in memory before sum can begin to work. This is much less efficient overall. Running the two versions with +RTS -s shows miserable garbage collection performance from the foldl version.
This is also a case where foldl' will not help. The added strictness of foldl' doesn't change the way the intermediate list is created. The head of the list remains unavailable until foldl' has finished, so the result will still be slower than with foldr.
I use the following rule to determine the best choice of fold
For folds that are a reduction, use foldl' (e.g. this will be the only/final traversal)
Otherwise use foldr.
Don't use foldl.
In most cases foldr is the best fold function because the traversal direction is optimal for lazy evaluation of lists. It's also the only one capable of processing infinite lists. The extra strictness of foldl' can make it faster in some cases, but this is dependent on how you'll use that structure and how lazy it is.
I don't think anyone's actually said the real answer on this one yet, unless I'm missing something (which may well be true and welcomed with downvotes).
I think the biggest different in this case is that foldr builds the list like this:
[0] ++ ([1] ++ ([2] ++ (... ++ [1000000])))
Whereas foldl builds the list like this:
((([0] ++ [1]) ++ [2]) ++ ... ) ++ [999888]) ++ [999999]) ++ [1000000]
The difference in subtle, but notice that in the foldr version ++ always has only one list element as its left argument. With the foldl version, there are up to 999999 elements in ++'s left argument (on average around 500000), but only one element in the right argument.
However, ++ takes time proportional to the size of the left argument, as it has to look though the entire left argument list to the end and then repoint that last element to the first element of the right argument (at best, perhaps it actually needs to do a copy). The right argument list is unchanged, so it doesn't matter how big it is.
That's why the foldl version is much slower. It's got nothing to do with laziness in my opinion.
The problem is that tail recursion optimization is a memory optimization, not a execution time optimization!
Tail recursion optimization avoids the need to remember values for each recursive call.
So, foldl is in fact "good" and foldr is "bad".
For example, considering the definitions of foldr and foldl:
foldl f z [] = z
foldl f z (x:xs) = foldl f (z `f` x) xs
foldr f z [] = z
foldr f z (x:xs) = x `f` (foldr f z xs)
That's how the expression "foldl (+) 0 [1,2,3]" is evaluated:
foldl (+) 0 [1, 2, 3]
foldl (+) (0+1) [2, 3]
foldl (+) ((0+1)+2) [3]
foldl (+) (((0+1)+2)+3) [ ]
(((0+1)+2)+3)
((1+2)+3)
(3+3)
6
Note that foldl doesn't remember the values 0, 1, 2..., but pass the whole expression (((0+1)+2)+3) as argument lazily and don't evaluates it until the last evaluation of foldl, where it reaches the base case and returns the value passed as the second parameter (z) wich isn't evaluated yet.
On the other hand, that's how foldr works:
foldr (+) 0 [1, 2, 3]
1 + (foldr (+) 0 [2, 3])
1 + (2 + (foldr (+) 0 [3]))
1 + (2 + (3 + (foldr (+) 0 [])))
1 + (2 + (3 + 0)))
1 + (2 + 3)
1 + 5
6
The important difference here is that where foldl evaluates the whole expression in the last call, avoiding the need to come back to reach remembered values, foldr no. foldr remember one integer for each call and performs a addition in each call.
Is important to bear in mind that foldr and foldl are not always equivalents. For instance, try to compute this expressions in hugs:
foldr (&&) True (False:(repeat True))
foldl (&&) True (False:(repeat True))
foldr and foldl are equivalent only under certain conditions described here
(sorry for my bad english)
For a, the [0.. 100000] list needs to be expanded right away so that foldr can start with the last element. Then as it folds things together, the intermediate results are
[100000]
[99999, 100000]
[99998, 99999, 100000]
...
[0.. 100000] -- i.e., the original list
Because nobody is allowed to change this list value (Haskell is a pure functional language), the compiler is free to reuse the value. The intermediate values, like [99999, 100000] can even be simply pointers into the expanded [0.. 100000] list instead of separate lists.
For b, look at the intermediate values:
[0]
[0, 1]
[0, 1, 2]
...
[0, 1, ..., 99999]
[0.. 100000]
Each of those intermediate lists can't be reused, because if you change the end of the list then you've changed any other values that point to it. So you're creating a bunch of extra lists that take time to build in memory. So in this case you spend a lot more time allocating and filling in these lists that are intermediate values.
Since you're just making a copy of the list, a runs faster because it starts by expanding the full list and then just keeps moving a pointer from the back of the list to the front.
Neither foldl nor foldr is tail optimized. It is only foldl'.
But in your case using ++ with foldl' is not good idea because successive evaluation of ++ will cause traversing growing accumulator again and again.
Well, let me rewrite your functions in a way that difference should be obvious -
a :: a -> [a] -> [a]
a = (:)
b :: [b] -> b -> [b]
b = flip (:)
You see that b is more complex than a. If you want to be precise a needs one reduction step for value to be calculated, but b needs two. That makes the time difference you are measuring, in second example twice as much reductions must be performed.
//edit: But time complexity is the same, so I wouldn't bother about it much.