簡體   English   中英

將高階函數從Python轉換為Haskell

[英]Convert higher order function from Python to 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中做到這一點,或者我在做夢?

下面的類型簽名是可選的:

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代碼的一對一映射。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM