如何摆脱额外的可能

时间:2012-04-02 00:31:02

标签: haskell monads functor maybe

我有一个可能失败的函数,因此它返回的值需要包含在Maybe中。它使用另一个也可能失败的函数,它也包含在Maybe中。问题是,为了使类型在中间计算中运行,我必须“过早地”提升函数以在Maybe上下文中工作。这导致我得到一个类型Maybe [Maybe Integer],当我想要的是Maybe [Integer]。有问题的函数是exptDecipherString函数,强制“过早”提升的函数是modularInverse函数。

import Data.Char
import Control.Applicative
import Control.Monad
import Math.NumberTheory.Powers

--Helpers

extendedGcd::Integer->Integer->(Integer, Integer)
extendedGcd a b | r == 0 = (0, 1)
                | otherwise = (y, x - (y * d))
                where
                    (d, r) = a `divMod` b
                    (x, y) = extendedGcd b r

modularInverse::Integer->Integer->Maybe Integer
modularInverse n b | relativelyPrime n b = Just . fst $ extGcd n b
                   | otherwise = Nothing
                   where
                        extGcd = extendedGcd

relativelyPrime::Integer->Integer->Bool
relativelyPrime m n = gcd m n == 1 

textToDigits::String->[Integer]
textToDigits = map (\x->toInteger (ord x - 97)) 

digitsToText::[Integer]->String
digitsToText = map (\x->chr (fromIntegral x + 97)) 

--Exponentiation Ciphers

exptEncipher::Integer->Integer->Integer->Maybe Integer
exptEncipher m k p | relativelyPrime k (m - 1) = Just $ powerMod p k m 
                   | otherwise = Nothing

exptDecipher::Integer->Integer->Integer->Maybe Integer
exptDecipher m q c | relativelyPrime q (m - 1) = Just $ powerMod c q m
                   | otherwise = Nothing

exptEncipherString::Integer->Integer->String->Maybe [Integer]
exptEncipherString m k p | relativelyPrime k (m - 1) = mapM (exptEncipher m k) plaintext
                         | otherwise = Nothing
    where
        plaintext = textToDigits p

exptDecipherString::Integer->Integer->[Integer]->Maybe String
exptDecipherString m k c | relativelyPrime k (m - 1) = fmap digitsToText plaintext
                         | otherwise = Nothing
    where
        q = modularInverse k (m - 1)
        plaintext = mapM (exptDecipher m <$> q <*>) (map pure c)

1 个答案:

答案 0 :(得分:6)

你应该首先尝试“X如何成为Y”的第一件事是hoogle。在这种情况下,它建议您使用join,这会将两个Maybe合并为一个。

通过一些代码重组,Maybe monad也可以用来帮助你。

当所有其他方法都失败时,请使用函数或带有模式匹配的case语句来推送自己的解决方案。