Multiline/-expression lambdas/anonymous functions?
See original GitHub issueNot a bug, but I could not find an answer anywhere. I mostly use R and very much like the functional approach. Python lacks proper pipes which are essential IMO to functional programming, so I was happy to discover Coconut!
Another essential part of functional programming (to me) is using a bunch of anonymous functions. For instance:
#mean intercor by column
mibi = function(x) {
v = sapply(1:ncol(x), function(col) {
col = x[, col]
(sum(col) - 1) / (ncol(x) - 1)
})
names(v) = colnames(x)
v
}
mibi(r_cors$correlations[-1, -1])
So, we make a function, mibi
, that finds the mean intercorrelation by column from a correlation matrix. The main part of the function is sapply
(an implicit loop that returns a vector [equivalent to a simple list in Python]), which is given an anonymous function that spans 2 lines.
In the Coconut documentation, there is an example of a lambda:
dubsums = map((x, y) -> 2*(x+y), range(0, 10), range(10, 20))
dubsums |> list |> print
Compared to the ordinary Python:
dubsums = map(lambda x, y: 2*(x+y), range(0, 10), range(10, 20))
print(list(dubsums))
But this is still only a one-liner lambda. How would one use multi-line/expression lambdas?
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (5 by maintainers)
Top GitHub Comments
Thanks for the issue! Currently, Coconut only supports one-line, not multi-line lambdas. Multi-line lambdas is definitely a feature I could add, however. The reason I haven’t yet is that in most cases I find that, since a
def
block is valid anywhere, it’s always possible to simply use that when one feels the need to use a multi-line lambda.I’m not opposed to adding multi-line lambdas, however. How does this look:
which would compile to something like
which should do exactly what you want. Do you think that would be helpful?
@Deleetdk @fredcallaway @ymeine I think I should be able to do this, the only issue is that I need to respect the Python rule that whitespace is ignored inside of parentheses. Thus, I think my solution will be to allow lambdas to contain statements, which includes Python’s syntax for putting multiple statements together of putting a semicolon between them. I could even have it check for the use of multiple statement syntax and automatically return the last one. Thus,
would be how you would write the above example (with the ability to insert whitespace wherever you wanted, as per the Python rule).