工作2个功能

时间:2017-10-02 17:02:42

标签: haskell

我将数字从八进制转换为十进制。我得到的数字为[Char],所以我决定先将其转换为[Int],然后将每个数字乘以8的相应幂。最后,我计划使用sum并获取我的数字十进制数。如何让两个函数逐个工作?

import Data.Char

charToDigit :: [Char] -> [Int] -- "123" -> [1,2,3]
charToDigit [] = []
charToDigit (x:xs) = digitToInt x : charToDigit xs

digitToDec :: [Int] -> [Int] -- [1,2,3] -> [64,16,3]
digitToDec [] = []
digitToDec (x:xs) = x * 8^(length xs) : digitToDec xs

octToDec :: [Char] -> Int
octToDec (x:xs) = charToDigit (x:xs) >>= digitToDec (x:xs) >>= sum (x:xs) -- "123" -> [1,2,3] -> [64,16,3] -> 64+16+3 = 83

2 个答案:

答案 0 :(得分:3)

使用普通函数组合运算符(.)来组成函数:

(.) :: (b -> c) -> (a -> b) -> a -> c

>>=是monadic绑定运算符:

(>>=) :: forall a b. m a -> (a -> m b) -> m b

您问题的解决方案很简单:

octToDec = sum . digitToDec . charToDigit

答案 1 :(得分:0)

仅出于练习目的,实现此功能的另一种方法可能是;

digits :: String -> [Int]
digits n | n == "" || n == "0" = []
         | otherwise           = ((++) <$> digits . show . (`div` 10) <*> return . (`rem` 10)) . read $ n

oct2dec :: String -> Int
oct2dec s = snd . foldr (\d r -> (1 + (fst r), snd r  + d * 8^(fst r))) (0,0) $ digits s

*Main> oct2dec "123"
83