是函数内部作用域导致的问题吗?

请教一下,下面的不同是什么原理导致的?函数内部作用域?

julia> str
"Turns hello_to_you into HelloToYou"

julia> function splitter(dlm)
           function r(str, dlm)
               split(str, dlm)
           end
           return r
       end
splitter (generic function with 1 method)

julia> str |> splitter('_')
ERROR: MethodError: no method matching (::var"#r#3")(::String)

Closest candidates are:
  (::var"#r#3")(::Any, ::Any)
   @ Main REPL[4]:2

Stacktrace:
 [1] |>(x::String, f::var"#r#3")
   @ Base .\operators.jl:907
 [2] top-level scope
   @ REPL[11]:1

julia> function splitter(dlm)
           function r(str)
               split(str, dlm)
           end
           return r
       end
splitter (generic function with 1 method)

julia> str |> splitter('_')
3-element Vector{SubString{String}}:
 "Turns hello"
 "to"
 "you into HelloToYou"

julia> function splitter(dlm)
           function r(str, dm)
               dm = dlm
               print("dm is", dm)
               split(str, dm)
           end
           return r
       end
splitter (generic function with 1 method)

julia> str |> splitter('_')
ERROR: MethodError: no method matching (::var"#r#8"{Char})(::String)

你要实现的应该是函数式的 Currying,可以直接这么写

str = "Turns hello_to_you into HelloToYou"
str |> Base.Fix2(split, '_')

然后,你报错的代码都有逻辑问题,

function splitter(dlm)
   function r(str, dlm)
       split(str, dlm)
   end
   return r
end

splitter('_') 返回一个二元函数,所以提示 No Method matching

1 个赞

不是作用域,是内部函数参数错误(假设你只是想要柯里化省个参数的话):
1、定义splitter

function splitter(dlm)
    function r(str) # !!! 😈
        split(str, dlm)
    end
    return r
end;

2、现在,

julia> sp = splitter("_")
(::var"#r#3"{String}) (generic function with 1 method)

3、调用:

julia> sp("Turns hello_to_you into HelloToYou")
3-element Vector{SubString{String}}:
 "Turns hello"
 "to"
 "you into HelloToYou"
2 个赞