计算每个元素出现的次数,并将它们 return 作为元组列表
Count the number of occurences of each element and return them as a list of tuples
我必须编写 elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
来计算列表中每个元素的出现次数,return 元组列表中的元素和结果。
例如:
elemFreqByFirstOcc "adbcba" == [('a',2),('d',1),('b',2),('c',1)]
elemFreqByFirstOcc [1,2,1,3,3,2,1,4,3,2,1,1,1,4,6,5] == [(1,6),(2,3),(3,3),(4,2),(6,1),(5,1)]
到目前为止,我有这段代码,如果列表中的所有元素只出现一次,它就可以正常工作,但是当一个元素出现多次时,每次都会对它们进行计数。 (所以对于第一个例子,它 returns [('a',2),('d',1),('b',2),('c',1),('b',1),('a',1)]
)
elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
elemFreqByFirstOcc [] = []
elemFreqByFirstOcc [x] = [(x, 1)]
elemFreqByFirstOcc (x:xs) = zip [x] [(length $ filter (==x) (x:xs))] ++ elemFreqByFirstOcc xs
您需要过滤掉您已经统计过的项目,因此:
elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
elemFreqByFirstOcc [] = []
elemFreqByFirstOcc (x:xs) = (x, length (filter (x ==) xs) + 1) : elemFreqByFirstOcc (<strong>filter (x /=) xs</strong>)
我必须编写 elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
来计算列表中每个元素的出现次数,return 元组列表中的元素和结果。
例如:
elemFreqByFirstOcc "adbcba" == [('a',2),('d',1),('b',2),('c',1)]
elemFreqByFirstOcc [1,2,1,3,3,2,1,4,3,2,1,1,1,4,6,5] == [(1,6),(2,3),(3,3),(4,2),(6,1),(5,1)]
到目前为止,我有这段代码,如果列表中的所有元素只出现一次,它就可以正常工作,但是当一个元素出现多次时,每次都会对它们进行计数。 (所以对于第一个例子,它 returns [('a',2),('d',1),('b',2),('c',1),('b',1),('a',1)]
)
elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
elemFreqByFirstOcc [] = []
elemFreqByFirstOcc [x] = [(x, 1)]
elemFreqByFirstOcc (x:xs) = zip [x] [(length $ filter (==x) (x:xs))] ++ elemFreqByFirstOcc xs
您需要过滤掉您已经统计过的项目,因此:
elemFreqByFirstOcc :: Eq a => [a] -> [(a, Int)]
elemFreqByFirstOcc [] = []
elemFreqByFirstOcc (x:xs) = (x, length (filter (x ==) xs) + 1) : elemFreqByFirstOcc (<strong>filter (x /=) xs</strong>)