繁体   English   中英

列表理解Haskell

[英]List comprehension 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

我认为问题出在我的理解力清单上。 有人可以指导我解决问题吗?

首先,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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM