【问题标题】:Get value of Maybe in Haskell [duplicate]在Haskell中获取Maybe的价值[重复]
【发布时间】:2015-10-12 22:55:37
【问题描述】:

我正在实现一个函数myFunction,它使用anotherFunction

anotherFunction 是一个无法修改的外部函数。它返回一个Maybe 类型的值。

myFunction 是一个递归函数,用于检查另一个myFunction 返回的值是Just 值还是Nothing。如果是Nothing则返回Nothing,否则会使用myFunction返回的纯值作为anotherFunction的参数。

基本上是这样的:

--These cannot be modified

data A = B | F a

anotherFunction :: x -> Maybe x
--Something here

myFunction :: A -> Maybe x 

--These can be modified
myFunction (F a) = {- if (myFunction a == Nothing) 
                        then Nothing 
                        else anotherFunction (pure value of (myFunction a)) -}

如何做到这一点?

【问题讨论】:

  • 使用案例陈述。
  • 在 Haskell 普通函数(不是构造函数)中通常以小写字母开头。
  • 不仅它们通常以小写开头,而且它们必须以小写开头才能在Haskell中被允许。我相应地编辑了问题。 — —(原则上,下划线也可以作为变量名的第一个字符,但不要这样做——the underscore has a special meaning.

标签: haskell maybe


【解决方案1】:

您可以使用case 匹配从MyFunction 返回的值:

case (myFunction a) of
  Nothing -> Nothing
  Just x -> anotherFunction x

不过更简洁的方法是使用>>=

(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
myFunction (f a) = (myFunction a) >>= anotherFunction

或者您可以使用do 表示法:

myFunction (f a) = do
  x <- myFunction a
  anotherFunction x

【讨论】:

    【解决方案2】:

    假设您有fg,它们都产生包装到类型MaybeJust 3Just "three"Nothing)中的值。您可以像这样组合两者:

    import Control.Monad
    
    f :: a -> Maybe b -- suppose these two are signatures of the given two functions
    g :: b -> Maybe c
    
    h :: a -> Maybe c -- this is the way you pass values from one
    h = f >=> g       -- to the other and bail out when you see Nothing
    

    我为abc 类型使用了方便的名称,以使组合更清晰,但请注意这些类型不受约束,a 在一个签名中与a在另一个签名中,实际类型是在具体上下文中使用这两个函数时决定的。

    由于您似乎没有对F a 构造函数中的a 施加任何限制,我想您希望它可能与A 不同。在这种情况下,函数 myFunction 不能具有 A -&gt; ... 类型,因为您试图将 a 作为参数传递。

    【讨论】:

      【解决方案3】:

      除非您在签名中有约束 Eq a =&gt; Maybe a,否则您将无法使用 ==。做这种事情的最好方法是使用case 声明:

      case m of
          Just x -> anotherFunction x
          Nothing -> Nothing
      

      这种模式对于Maybe 非常常见,它形成了MaybeMonad 实例,为您提供return x = Just xf &gt;&gt;= x = case x of Just a -&gt; f a; Nothing -&gt; Nothing 函数。

      【讨论】:

      • 别叫它maybe。这是 Prelude 中一个函数的名称。
      • @Zeta 谢谢,已更改。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2021-11-26
      • 2022-01-12
      • 2012-09-19
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多