将高阶函数从 Python 转换为 Haskell

发布于 2024-09-27 09:02:46 字数 578 浏览 1 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱情眠于流年 2024-10-04 09:02:46

下面的类型签名是可选的:

stagger :: [a] -> Int -> [[a]]
stagger l w
    | length l >= w  =  take w l : stagger (tail l) w
    | otherwise      =  []

pleat :: ([a] -> b) -> [a] -> Int -> [b]
pleat f l w = map f $ stagger l w

main = do
    print $ pleat (\[x, y] -> x+y) [0..9] 2
    print $ pleat (\[x, y, z] -> x*y/z) [3..12] 3
    print $ pleat (\[x] -> "~" ++ show x ++ "~") [0..9] 1
    print $ pleat (\[a, b, x, y] -> a+b == x+y) [3, 2, 4, 1, 5, 0, 9, 9, 0] 4

这个想法是该函数明确将未知长度的列表作为参数,因此它不是非常类型安全的。但它几乎是 Python 代码的一对一映射。

The type signatures below are optional:

stagger :: [a] -> Int -> [[a]]
stagger l w
    | length l >= w  =  take w l : stagger (tail l) w
    | otherwise      =  []

pleat :: ([a] -> b) -> [a] -> Int -> [b]
pleat f l w = map f $ stagger l w

main = do
    print $ pleat (\[x, y] -> x+y) [0..9] 2
    print $ pleat (\[x, y, z] -> x*y/z) [3..12] 3
    print $ pleat (\[x] -> "~" ++ show x ++ "~") [0..9] 1
    print $ pleat (\[a, b, x, y] -> a+b == x+y) [3, 2, 4, 1, 5, 0, 9, 9, 0] 4

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文