使用head,tail和null在列表中的元素的产品

时间:2016-04-19 09:37:46

标签: haskell

所以基本上我应该使用head来获取第一个元素并乘以并使用tail和null遍历列表。我对haskell很新,所以我根本不理解流量控制。下面的代码已经可以工作了,我只需要弄清楚在哪里使用tail并遍历列表。

module Blueprint where
import Prelude


x=1
prod :: [Integer] -> Integer
prod n 
|null n == True = 0
|null n== False = x*head n 

添加一些伪代码:

x=1
prod :: [Integer] -> Integer
prod n 
|null n == True = 0
|null n== False = x*head n  do tail n repeat until null n == true   

任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:6)

你差不多了!您只需递归调用prod来获取列表尾部的乘积,然后将结果的列表头部相乘。

prod :: [Int] -> Int
prod xs
    | null xs = 1
    | otherwise = head xs * prod (tail xs)  -- note recursive call to prod

顺便提一下,使用模式匹配来解构列表更加惯用,而不是手动调用headtailnull

prod [] = 1
prod (x:xs) = x * prod xs

希望您能看到这与上面的代码相同。

Terser仍然将prod表示为 fold

prod = foldr (*) 1

foldr是标准的Haskell习惯用法,用于一次使用一个列表。它的定义如下:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f acc [] = acc
foldr f acc (x:xs) = f x acc (foldr f acc xs)

替换*的{​​{1}}和f替换该定义中的1,您将从上方恢复acc