如何找到列表中最长的单词?

时间:2011-01-16 21:03:40

标签: haskell

我无法用一种功能性的思维方式来解决这个问题,这种方式也可以用于非常长的列表。如果您有以下列表:

["one", "two", "three", "four", "five"]

我可以通过以下方式判断最长单词的长度是多少:

maximum $ map length ["one", "two", "three", "four", "five"]

如何修改前一个语句以返回字符串 three

6 个答案:

答案 0 :(得分:38)

使用maximumByoncompare,您可以编写如下表达式:

import Data.List (maximumBy)
import Data.Function (on)

maximumBy (compare `on` length)  ["one", "two", "three", "four", "five"]

答案 1 :(得分:12)

顺便说一下,如果一个没有现成的maximumBy,一个简单的方法就是装饰 - 排序 - 不合理的模式/习语(它也适用于其他语言,如Python或Scheme):

snd $ maximum $ map (\x -> (length x, x)) ["one", "two", "three", "four", "five"]

但由于原始有效载荷也是sort-key的一部分,因此结果并不总是第一次出现最长的单词(在这种情况下,只有一个单词的长度最长)

答案 2 :(得分:9)

这个函数(甚至库)似乎并不为人所知,但Haskell实际上有一个名为Data.Ord的模块,它包含函数comparing,几乎就像使用Data.Function.on一样在最佳答案中,除了代码最终更加惯用。

g>import Data.Ord
g>import Data.List
g>let getLongestElement = maximumBy (comparing length)
getLongestElement :: [[a]] -> [a]
g>getLongestElement ["one", "two", "three", "four", "five"]
"three"

代码实际上读起来像英文。 “通过比较长度获得最大值。”

答案 3 :(得分:3)

maximumBy (\x -> (x, length x))fstsnd在简单的构图中可以解决这个问题。

答案 4 :(得分:1)

要计算length a,您需要遍历整个列表a。在这个特定的用例中,你只关心最长的单词,而不是它们究竟有多长,所以你可以编写一个只在每个列表中需要的函数来确定哪一个是最长的。这可以为您节省一些处理时间:

module Main where

main = putStrLn $ longestWordInList ["one", "two", "three", "four"]

longestWordInList = go ""
  where go result [] = result
        go result (x:xs) = let result' = longestWord result x in
                               result' `seq` go result' xs

longestWord a b = go a b a b
  where go a _ _ [] = a
        go _ b [] _ = b
        go a b (_:as) (_:bs) = go a b as bs

答案 5 :(得分:0)

foldl (\accmax xs -> if length accmax < length xs then xs else accmax) [] ["one", "two", "three", "four", "five"]
相关问题