我有一个函数triple_count
,它计算3个整数的总和。我试图使用这个函数来构造一个新函数,它接受一个整数输入列表并返回一个总和列表。
最初我试过了:
triples :: [Int] -> [Int]
triples xs
| length xs < 3 = []
| otherwise = triple_count (take 3 xs) : triples (drop 3 xs)
哪个失败,因为三重计数的签名为Int -> Int -> Int -> [Int]
而非[Int] -> [Int]
。
triples :: [Int] -> [Int]
triples xs
| length xs < 3 = []
| otherwise = (triple_count p1 p2 p3) : triples (drop 3 xs)
where params = take 3 xs
p1 = params !! 0
p2 = params !! 1
p3 = params !! 2
是否有更好/更通用的方法将列表拆分为单独的参数而不是单独调用它们?
答案 0 :(得分:4)
是否有更好/更通用的方法将列表拆分为单独的参数而不是单独调用它们?
更具可读性的可能是:
triples :: [Int] -> [Int]
triples (a:b:c:rest) = triple_count a b c: triples rest
triples _ = []