列表理解Haskell

时间:2014-11-28 20:22:40

标签: list haskell

我有一个练习的问题,我需要使用列表理解,问题是这样的: 我收到了列表,我必须计算并返回另一个列表,其中包含每个数字的出现次数o(0-5)。

例如:

[3,3,2,0,3,4] the output should be [1,0,1,2,1,1], 
-number 0 only happens 1 time
-number 1 never occurs 
-numer 2 occurs 1 time 
-number 3 occurs 2 times 
-and so on

我尝试了什么:

nTimes = [ y| x<-[0..5], y<- (occurs x [3,3,2,0,3,4])]


occurs n [] = 0
occurs n (x:xs) | n == x = 1+ occurs ( n xs)
                | otherwise = occurs n xs

我认为问题在于我的理解清单。有人可以指导我解决方案吗?

1 个答案:

答案 0 :(得分:1)

首先,y不是列表,因此您必须通过let引入它或在正文中使用它。

nTimes = [ y| x<-[0..5], let y = occurs x [3,3,2,0,3,4]]
-- or
nTimes = [ occurs x [3,3,2,0,3,4] | x<-[0..5]]

函数本身在递归调用中只有一个小错误

occurs n [] = 0
occurs n (x:xs) | n == x = 1 + occurs n xs
                | otherwise = occurs n xs

或者,更有趣的写作方式

occurs n x = length $ filter (== n) x