假设我有一个函数,它接受3个参数作为输入。如何在Elm中部分应用此函数,以便它接受第一个和最后一个参数并等待第二个参数返回最终结果?
这可以在Ramda与R.__
完成,命名为placeholer
。
你可以将它包装在一个具有你想要的形状的lambda函数中,这也是任何其他方式产生的:
\y -> f "x" y "z"
在一种讨论的语言中,我发现需要这样做非常罕见,因此专门为此用例添加语法糖似乎是不必要的。
正如glennsl所说,你可以使用你想要的参数顺序将你的函数包装在另一个函数中。他的回答假设您静态地知道第一个和第三个参数是什么,如果不这样做,但只是想部分应用第一个和第三个参数,然后应用第二个参数,你可以采取像这样的函数,
joinThree : String -> String -> String -> String
joinThree first second third =
first ++ second ++ third
并将其包装在一个调用第一个函数的新函数中,但使用不同的参数顺序,
joinThreeWrapper : String -> String -> String -> String
joinThreeWrapper first third second =
joinThree first second third
这允许你像这样调用这个函数,
welcomeToNeverland : String -> String
welcomeToNeverland name =
let
myGreeting = joinThreeWrapper "Welcome " " to Neverland"
in
myGreeting name
然后就可以像使用它一样
text (welcomeToNeverland "Wendy")
-- Welcome Wendy to Neverland
像这样写joinThreeWrapper
可以更容易地将你的函数映射到列表上,比如
greetMany : List String -> List String
greetMany names =
List.map (joinThreeWrapper "Welcome " ", this is our town. ") names
这样你就可以
text (List.map (++) (greetMany ["Jesse", "Carl"]))
-- Welcome Jesse, this is our town. Welcome Carl, this is our town.
您可以使用核心Basics模块中的flip。
例如:
> append3 x y z = x ++ y ++ z
<function> : appendable -> appendable -> appendable -> appendable
> hello = flip (append3 "Hello, ") "!"
<function> : String -> String
> hello "world"
"Hello, world!" : String