我应该如何使用 maximumBy 和 compare 来实现我的功能?
How should I use maximumBy and compare to implement my function?
我必须在 Haskell 中进行 LZW 压缩,但我在搜索最长前缀时有点卡住了,因为我必须结合使用 maximumBy
和 compare
函数.
函数签名应如下所示:
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
但肯定有问题。
这是将要执行的操作:
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
它可以写得更短但可读性较差。
@Eugene Sh 的解决方案的较短版本:
import Data.List
import Data.Ord
longest = maximumBy (comparing (length . snd) <> flip (comparing fst))
我必须在 Haskell 中进行 LZW 压缩,但我在搜索最长前缀时有点卡住了,因为我必须结合使用 maximumBy
和 compare
函数.
函数签名应如下所示:
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
但肯定有问题。
这是将要执行的操作:
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
它可以写得更短但可读性较差。
@Eugene Sh 的解决方案的较短版本:
import Data.List
import Data.Ord
longest = maximumBy (comparing (length . snd) <> flip (comparing fst))