简化嵌套可能模式匹配 [英] Simplifying nested Maybe pattern matching

查看:131
本文介绍了简化嵌套可能模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中有以下结构:

  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

这篇关于简化嵌套可能模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆