我应该如何使用maximumBy并比较来实现我的功能?

时间:2015-03-16 14:38:26

标签: haskell compare

我必须在Haskell中进行LZW压缩,并且我在搜索最长前缀时有点困难,因为我必须使用maximumBycompare函数的组合。

函数签名应该如下:

longest :: [(Int, String)] -> (Int, String)

以下是一些描述要求的测试:

test_longest =
  [ longest [(30, "a"), (20, "abc"), (15, "ab")]  == (20, "abc")
  , longest [(30, "a"), (20, "abc"), (15, "abc")] == (15, "abc")
  ]

任何帮助将不胜感激。

我在试图理解这个问题时想出的是:

longest (x:xs) = maximumBy (compare (length) x) xs

但有些事情肯定是关闭的。

2 个答案:

答案 0 :(得分:1)

@Eugene Sh的解决方案的简化版本:

import Data.List
import Data.Ord

longest = maximumBy (comparing (length . snd) <> flip (comparing fst))

答案 1 :(得分:0)

这是做什么的:

import Data.List

compareEntry :: (Int, [Char]) -> (Int, [Char]) -> Ordering
compareEntry (i1, s1) (i2, s2)
    | len1 > len2 = GT   -- First compare the length of the strings
    | len1 < len2 = LT
    | i1 < i2 = GT       -- If they are equal, compare the indices
    | i2 > i1 = LT       -- (mind the reversed order, since you want the lowest index)
    | otherwise = EQ
    where 
        len1 = length s1
        len2 = length s2

longest = maximumBy compareEntry

它可以用更短但不太可读的方式编写。