Haskell - 返回字符串中使用的a-Z字符的数量 [英] Haskell - Returning the number of a-Z characters used in a string

查看:392
本文介绍了Haskell - 返回字符串中使用的a-Z字符的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一整天都在Haskell网站上使用这个页面,它对学习列表函数非常有帮助: http://www.haskell.org/haskellwiki/How_to_work_on_lists



我现在的任务是编写一个单行语句,返回在字符串中使用的字符(aZ)。我似乎无法在上面的网页或互联网上的任何其他地方找到任何帮助



我知道如何使用长度nameoflist来计算字符串中的字符,但是我'我不知道如何计算已使用的aZ字符的数量,例如'starT to'应该返回6



任何帮助表示感谢,谢谢

解决方案

替代@ Sibi的完美答案是使用 sort
$ Data.List 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

或者如果您想使用更优雅的Control.Arrow表单

  elemFrequency = map(head&& length)。组。 

它可以用作

 > (''',1),('''',1),('''',3),('''') 'o',2),('r',1),('w',1)] 


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 sort and group from Data.List:

numUnique :: Ord a => [a] -> Int
numUnique = length . group . sort

This imposes the tighter restriction of 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

Or if you want to use the more elegant Control.Arrow form

elemFrequency = map (head &&& length) . group . sort

It can be used as

> elemFrequency "hello world"
[(' ',1),('d',1),('e',1),('h',1),('l',3),('o',2),('r',1),('w',1)]

这篇关于Haskell - 返回字符串中使用的a-Z字符的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆