在Haskell中如何检查字符串是否小于另一个字符串?

kjv*_*kjv 6 string haskell compare

我有两个字符串作为Haskell函数的参数.

s1小于s2如果s1是短于s2或如果它们具有相同的长度和s1按字典顺序小于s2.

我如何在Haskell中实现它?

Luk*_*ard 9

我会使用以下内容:

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


GS *_*ica 7

一次通过解决方案:

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)


And*_*are 5

试试这个:

compare s1 s2
Run Code Online (Sandbox Code Playgroud)

(这会返回LT,EQ或GT).