简体   繁体   中英

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:

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM