我正在尝试以一种更强制性的方式表达一系列链接的呼叫。例如,image我们有一个函数,它接受一个列表和一个元素,并将该元素追加到列表的末尾:
let insert l e =
l @ [e]
我想一次插入几个元素。执行此操作的功能方法可能是:
let myList = insert (insert (insert [] 3) 4) 5)
最近,我了解了|>
运算符,它有助于提高表达能力。与curring一起使用,可以导致干净的链接。问题在于我们需要首先绑定第二个参数。这需要定义一个函数来反转参数(实际上是|>
:P的作用):
let myList =
let insertIn l e = insert e l in
[] |>
insertIn 3 |>
insertIn 4 |>
insertIn 5
;;
这几乎是我想要的,除了需要定义insertIn
。有没有更清洁的方法可以做到这一点?
我希望有一个像$
这样的特殊运算符可以表示前一个函数的返回值:
let myList =
[] |>
insert $ 3 |>
insert $ 4 |>
insert $ 5
;;
在Haskell中常见的一种可能方法是使用flip
:
let flip f x y = f y x
let myList =
[] |>
flip insert 3 |>
flip insert 4 |>
flip insert 5
但是,实际上,如果insert
函数是您自己编写的,那么您应该考虑以下列任何一种方式更改其定义:
翻转参数,使列表排在最后,也就是“标准库样式”:
let insert e l =
l @ [e]
let myList =
[] |>
insert 3 |>
insert 4 |>
insert 5
使用命名参数,该参数可让您无序传递(也称为“核心样式”):
let insert l ~elt:e =
l @ [e]
let myList =
[] |>
insert ~elt:3 |>
insert ~elt:4 |>
insert ~elt:5
(另外请注意:您insert
的效率很低,因为您l
每次都复制整个内容;列表的设计是通过在元素前面添加::
,而不是在后面添加来构造的。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句