Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can Julia pass an argument to an inner anonymous function?

I’m trying to pass an argument to an anonymous function in map() in a particular way (see code examples).

The following code in Julia…

function f(x,y):map((z)->z+y,x) end
print(f([1,2,3],1))

returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MethodError: objects of type Symbol are not callable
Stacktrace:
 [1] f(x::Vector{Int64}, y::Int64)
   @ Main .\REPL[1]:1
 [2] top-level scope
   @ REPL[5]:1

Same code translated to Python…

def f(x,y):
    return map(lambda z:z+y,x)
print(list(f([1,2,3],1)))

works as expected:
[2, 3, 4].

Why is the same block of code misbehaving in Julia in contrast to Python and what is the workaround?

>Solution :

It’s just a syntax issue: Julia function declarations don’t use a colon before the function body.

julia> function f(x,y) map((z)->z+y,x) end
f (generic function with 2 methods)

julia> print(f([1,2,3],1))
[2, 3, 4]

Or more readably,

julia> function f(x, y)
         map(z -> z .+ y, x)
       end
f (generic function with 2 methods)

julia> print(f([1,2,3],1))
[2, 3, 4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading