将高阶函数从 Python 转换为 Haskell
我有以下代码:
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
if __name__=="__main__":
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
重要部分:Pleat 接受任何函数和任何序列,并将该序列中的前几个元素作为参数传递到接收到的函数中。
有没有办法在 Haskell 中做到这一点还是我在做梦?
I have the following code:
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
if __name__=="__main__":
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
Important part: Pleat takes any function and any sequence and passes the first handful of elements from that sequence into the received function as parameters.
Is there a way to do this in Haskell or am I dreaming?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面的类型签名是可选的:
这个想法是该函数明确将未知长度的列表作为参数,因此它不是非常类型安全的。但它几乎是 Python 代码的一对一映射。
The type signatures below are optional:
The idea is that the function is explicit about taking a list of unknown length as an argument, so it is not very type-safe. But it is pretty much a 1-to-1 mapping of the Python code.