1

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

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)
4

1 回答 1

6

对于“X 如何变成 Y”,您通常应该尝试的第一件事是hoogle。在这种情况下,它建议您使用join,它将两个Maybes 合并为一个。

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

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

于 2012-04-02T00:40:28.730 回答