Home > Software design >  Can Julia pass an argument to an inner anonymous function?
Can Julia pass an argument to an inner anonymous function?

Time:06-09

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?

CodePudding user response:

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]
  • Related