1
我只是Haskell的初學者,我嘗試在Haskell中做cryptopals加密挑戰。檢查Maybe值
我寫了下面的代碼:
import Data.Char
nibbleToInt :: Char -> Int
nibbleToInt c
| ('0' <= c && c <= '9') = (ord c) - 48
| ('a' <= c && c <= 'f') = (ord c) - 87
| ('A' <= c && c <= 'F') = (ord c) - 55
| otherwise = error "Boom"
hexToInt :: String -> Int
hexToInt (x:y:[]) = nibbleToInt x * 16 + nibbleToInt y
hexToInt _ = error "Boom"
hexToInts :: String -> [Int]
hexToInts [] = []
hexToInts (n1:n2:ns) = [hexToInt $ [n1] ++ [n2]] ++ (hexToInts ns)
hexToInts _ = error "Boom"
main = do
print $ hexToInts "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
此代碼似乎工作,但我相信它可以提升!
我重構了nibbleToInt
功能使用Maybe
:
nibbleToInt :: Char -> Maybe Int
nibbleToInt c
| ('0' <= c && c <= '9') = Just ((ord c) - 48)
| ('a' <= c && c <= 'f') = Just ((ord c) - 87)
| ('A' <= c && c <= 'F') = Just ((ord c) - 55)
| otherwise = Nothing
然而,然後,我不知道如何重寫功能HEXTOINT,因爲它調用nibbleToInt
功能的兩倍,它返回Maybe Int
。我不知道如何測試這兩個值。
任何幫助是值得歡迎的,因爲我不知道我身邊的任何哈斯克爾程序員......
適用的組成是你所需要的。在Hoogle中查找'liftA2'或'<*>'和'<$>'。 – Jubobs
非常感謝您的回答! – ols