简体   繁体   English

在Haskell中获取列表中单词的长度

[英]Getting length of words in list in Haskell

I started to write a couple functions where I could count specific words in a sentence and so on, but now I need to count the lengths of the words in a list. 我开始编写一些函数,可以计算句子中的特定单词,依此类推,但是现在我需要计算列表中单词的长度。 So I have a list where each element is a word and want to count the characters of this word. 因此,我有一个列表,其中每个元素都是一个单词,并希望计算该单词的字符。 I couldn't find any solution to do that, since Haskell doesn't use loops. 我找不到任何解决方案,因为Haskell不使用循环。 Is there anyway to do this? 反正有这样做吗?

If you think you need a loop when working in Haskell, you're probably looking for recursion. 如果您认为在Haskell中工作时需要循环,则可能正在寻找递归。 We'll want to recurse through the list of strings, applying the length function to each one. 我们要遍历字符串列表,将length函数应用于每个字符串。 The general pattern of recursion through a list where a function is applied to each value (which you'll become very familiar with as you work through Haskell) looks roughly like this: 通过列表进行递归的一般模式,其中将函数应用于每个值(在使用Haskell时会变得非常熟悉):

func f []     = []
func f (x:xs) = f x : func f xs

So we could solve the problem that way (specializing the function, rather than accepting it as an argument): 因此,我们可以通过这种方式解决问题(专门化功能,而不是将其作为参数接受):

wordLengths :: [String] -> [Int]
wordLengths []     = []
wordLengths (x:xs) = length x : wordLengths xs

However, since this behavior is so common, there exists a function map that takes care of all of this for us. 但是,由于这种行为非常普遍,因此存在一个功能map可以为我们解决所有这些问题。 Its type signature is (a -> b) -> [a] -> [b] , so we know to pass it a function ( length ) and a list of things (our String s). 它的类型签名是(a -> b) -> [a] -> [b] ,因此我们知道将一个函数( length )和一个事物列表(我们的String )传递给它。 If we map the length function to each value in your list of strings, we'll get your desired result: 如果将length函数map到您的字符串列表中的每个值,我们将获得您想要的结果:

wordLengths :: [String] -> [Int]
wordLengths = map length

Example usage: 用法示例:

ghci>> wordLengths ["abc","defg"]
[3,4]

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

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