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

``````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)
``````

``````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 个赞