如何摆脱额外的可能

Jos*_*sto 1 monads haskell 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)
Run Code Online (Sandbox Code Playgroud)

Tho*_*son 6

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

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

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

  • @JoshInfiesto您的查询几乎是正确的!你刚忘记了一些括号.尝试`Monad m => m(ma) - > ma`,然后考虑该查询的工作原理. (3认同)