简体   繁体   English

列表理解Haskell

[英]List comprehension Haskell

I'm having problem with one exercise, where i need to use the list comprehension, the problem is something like this: I receive the list, and i have to count and return another list with the number of occurrences of each number o ( 0-5). 我在一次练习中遇到问题,需要使用列表理解,问题是这样的:我收到列表,并且我必须计数并返回另一个列表,每个列表的出现次数为o(0 -5)。

For example: 例如:

[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

What i have tried: 我试过的

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

I think the problem is with my comprehension list. 我认为问题出在我的理解力清单上。 Can someone guide me to the solution? 有人可以指导我解决问题吗?

First of all, y is not a list, so you have to introduce it via let or use it in the body. 首先,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]]

The function itself only has a minor mistake in its recursive call 函数本身在递归调用中只有一个小错误

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

or, a more fun way to write it 或者,一种更有趣的方式来编写它

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

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

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