kjv*_*kjv 6 string haskell compare
我有两个字符串作为Haskell函数的参数.
s1小于s2如果s1是短于s2或如果它们具有相同的长度和s1按字典顺序小于s2.
我如何在Haskell中实现它?
我会使用以下内容:
smaller :: String -> String -> Bool
smaller s1 s2 | len1 /= len2 = (len1 < len2)
| otherwise = (s1 < s2)
where (len1, len2) = (length s1, length s2)
Run Code Online (Sandbox Code Playgroud)
这是Hugs中的示例运行:
Main> smaller "b" "aa" True Main> smaller "aa" "b" False Main> smaller "this" "that" False Main> smaller "that" "this" True
一次通过解决方案:
lengthcompare :: Ord a => [a] -> [a] -> Ordering
lengthcompare = lc EQ
where
lc lx [] [] = lx
lc _ [] _ = LT
lc _ _ [] = GT
lc EQ (v:vs) (w:ws) = lc (compare v w) vs ws
lc lx (_:vs) (_:ws) = lc lx vs ws
smaller :: Ord a => [a] -> [a] -> Bool
smaller s1 s2 = lengthcompare s1 s2 == LT
Run Code Online (Sandbox Code Playgroud)