Haskell - 返回字符串中使用的a-Z字符的数量 [英] Haskell - Returning the number of a-Z characters used in a string
问题描述
我一整天都在Haskell网站上使用这个页面,它对学习列表函数非常有帮助: http://www.haskell.org/haskellwiki/How_to_work_on_lists
我现在的任务是编写一个单行语句,返回在字符串中使用的字符(aZ)。我似乎无法在上面的网页或互联网上的任何其他地方找到任何帮助
我知道如何使用长度nameoflist来计算字符串中的字符,但是我'我不知道如何计算已使用的aZ字符的数量,例如'starT to'应该返回6
任何帮助表示感谢,谢谢
替代@ Sibi的完美答案是使用 这会限制 或者如果您想使用更优雅的Control.Arrow表单 它可以用作 I've been using this page on the Haskell website all day and its been really helpful with learning list functions: http://www.haskell.org/haskellwiki/How_to_work_on_lists My task at the moment is to write a single line statement that returns the number of characters (a-Z) that are used in a string. I can't seem to find any help on the above page or anywhere else on the internet I know how to count characters in a string by using length nameoflist, but I'm not sure how I would go about counting the number of a-Z characters that have been used, for example 'starT to' should return 6 Any help is appreciated, thanks An alternative to @Sibi's perfectly fine answer is to use a combination of This imposes the tighter restriction of Or if you want to use the more elegant Control.Arrow form It can be used as
这篇关于Haskell - 返回字符串中使用的a-Z字符的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! sort $ c
$
p $ p> numUnique :: Ord a => [a] - > Int
numUnique = length。组。
$ b $ p Ord
而不仅仅是 Eq
,但我相信可能会稍微快一些,因为 nub
并不知道它的效率。您还可以使用一个非常类似的函数来计算列表中每个唯一元素的数量:
elemFrequency :: Ord a = > [a] - > [(a,Int)]
elemFrequency = map(\ s - >(head s,length s))。组。 sort
elemFrequency = map(head&& length)。组。
> (''',1),('''',1),('''',3),('''') 'o',2),('r',1),('w',1)]
sort
and group
from Data.List
:numUnique :: Ord a => [a] -> Int
numUnique = length . group . sort
Ord
instead of just Eq
, but I believe might be somewhat faster since nub
is not known for its efficiency. You can also use a very similar function to count the number of each unique element in the list:elemFrequency :: Ord a => [a] -> [(a, Int)]
elemFrequency = map (\s -> (head s, length s)) . group . sort
elemFrequency = map (head &&& length) . group . sort
> elemFrequency "hello world"
[(' ',1),('d',1),('e',1),('h',1),('l',3),('o',2),('r',1),('w',1)]