计算字符串Haskell中字符的出现次数 [英] Count occurrences of character in a string Haskell

查看:363
本文介绍了计算字符串Haskell中字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试确定如何计算 char 的出现次数是 string 。我将它存储在 [char,count] 列表中。

countChars :: String - > [(Char,Int)]



我是新手,正在学习Haskell,因此非常感谢所有帮助。

解决方案

给你一个美味

 > ('a',4),('d',3),('e',1),((地图(头部&长度).group。sort) 'f',3),('s',2)] 

/ p>

您可以轻松定义您的头&&&如果该语法是不熟悉的话,那么它就是一个长度。

 > head_and_length x =(head x,length x)

组可以递归写入

  group [] = [] 
group(x:xs)=(x:ys):group zs
where(ys ,zs)=(takeWhile(== x)xs,dropWhile(== x)xs)

采取尽可能多的匹配元素,并递归应用于其余的元素,直到没有剩下。请注意,这个定义需要相同的元素是连续的,这就是为什么需要排序的原因。



编写一个复杂函数是不推荐的,最好实现小特性分开(也许使用现有的功能),可以独立测试并创建这些作为最终解决方案的组合。


Trying to determine how to count the occurrences of a char is a string. I was it to be stored in a list [char,count].

countChars :: String -> [(Char, Int)]

I'm new and learning Haskell so any help is much appreciated.

解决方案

to give you a taste

> (map (head &&& length) . group . sort) "asdfasdfaeadf"
[('a',4),('d',3),('e',1),('f',3),('s',2)]

after bunch or imports.

You can easily define your head &&& length, if that syntax is unfamiliar.

> head_and_length x = (head x, length x)

group can be written recursively

group [] = []
group (x:xs) = (x:ys) : group zs
    where (ys,zs) = (takeWhile (==x) xs, dropWhile (==x) xs)

take as many matching elements as possible and recursively apply on the remaining elements until nothing left. Note that this definition requires same elements to be contiguous, that's why a sort is required.

Writing a complex function is one piece is not recommended, it's better to implement small features separately (and perhaps use the existing functions) which can be independently tested and create a composition of these as a final solution.

这篇关于计算字符串Haskell中字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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