问题描述
在我的代码中有以下结构:
f :: Maybe A - > X
f a = a
的情况a无 - > x
(Just b) - >
的情况b没有 - > y
(Just c) - >案例c的
无 - > z
(Just d) - > d
我没有看到一种明显的方法来简化它,而不是使用嵌套的也许
函数,这不会使整个事情看起来好多了。有没有什么聪明的,但仍然可以理解的技巧可以让这个构造更加优雅?解析方案
在我的代码中有以下结构:
f :: Maybe A - > X
f a = a
的情况a无 - > x
(Just b) - >
的情况b没有 - > y
(Just c) - >案例c的
无 - > z
(Just d) - > d
我没有看到一种明显的方法来简化它,而不是使用嵌套的也许
函数,这不会使整个事情看起来好多了。有没有什么聪明的,但仍然可以理解的技巧可以让这个构造更加优雅?解析方案
UPDATED 2
Monad或者
适合您
import Data.Maybe(也许)
maybeE :: e - >也许是 - >或者e
maybeE e =也许(左e)右
f ::可能(可能(也许是d)) - > ed ed
fa = maybeE xa
>> = maybeE y
>> = maybeE z
UPDATED 3
如果我们不想要
type,我们可以重写函数:
$ p $ import Data.Either()
或者'= id id
f :: Maybe(Maybe(Maybe d)) - > d
fa ='$ maybeE xa
>> = maybeE y
>> = maybeE z
I have the following construct in my code:
f :: Maybe A -> X
f a = case a of
Nothing -> x
(Just b) -> case b of
Nothing -> y
(Just c) -> case c of
Nothing -> z
(Just d) -> d
I'm not seeing an obvious way to simplify this instead of using nested maybe
functions, which wouldn't make the whole thing look much better. Are there any clever - but still understandable - tricks that would help make this construct more "elegant"?
UPDATED 2
Monad Either
is for you
import Data.Maybe (maybe)
maybeE :: e -> Maybe a -> Either e a
maybeE e = maybe (Left e) Right
f :: Maybe (Maybe (Maybe d)) -> Either e d
f a = maybeE x a
>>= maybeE y
>>= maybeE z
UPDATED 3
If we want to have not Either
type, we could rewrite function:
import Data.Either(either)
either' = either id id
f :: Maybe (Maybe (Maybe d)) -> d
f a = either' $ maybeE x a
>>= maybeE y
>>= maybeE z
这篇关于简化嵌套可能模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!