haskell如何[a] ++ [b]与may

时间:2014-11-15 20:43:55

标签: haskell

我想做Maybe Substitution -> Maybe Substitution -> Maybe Substitution 其中type Substitution = [(Variable,Terme)]但是当我使用++时,我有这个

/Users/michel/Documents/workspace/2LammensMichelInterpreteurProlog/Setup.hs:65:58:
    Couldn't match expected type ‘[a0]’
                with actual type ‘Maybe Substitution’
    In the first argument of ‘(++)’, namely ‘listsub’
    In the expression: listsub ++ listsub

/Users/michel/Documents/workspace/2LammensMichelInterpreteurProlog/Setup.hs:65:58:
    Couldn't match expected type ‘Maybe Substitution’
                with actual type ‘[a0]’
    In the expression: listsub ++ listsub
    In an equation for ‘substition’:
        substition ((V variable), (F nom1 lTerme1)) listsub
          = listsub ++ listsub

/Users/michel/Documents/workspace/2LammensMichelInterpreteurProlog/Setup.hs:65:69:
    Couldn't match expected type ‘[a0]’
                with actual type ‘Maybe Substitution’
    In the second argument of ‘(++)’, namely ‘listsub’
    In the expression: listsub ++ listsub
Failed, modules loaded: none.

2 个答案:

答案 0 :(得分:1)

(++)适用于列表,而不是Maybe,您需要解除它

以下是如何使其适用于Maybe String

import Control.Monad
(liftM2 (++)) (Just "aa") (Just "bb")

您可以通过定义新的运算符来使其看起来更好。

(+++) = liftM2 (++)

然后像

一样使用它
Just "aa" +++ Nothing

答案 1 :(得分:1)

Maybe是一个Applicative,因此您可以使用liftA2等函数将函数应用于Maybe s内的值。

例如(如果您的变量和术语是字符串):

import Control.Applicative

liftA2 (++) (Just [("foo", "bar")])  (Just [("FOO", "BAR")])
-- Just [("foo","bar"),("FOO","BAR")]

或等效地,使用<$><*>中缀运算符:

(++) <$> Just [("foo", "bar")]  <*> Just [("FOO", "BAR")]
-- Just [("foo","bar"),("FOO","BAR")]

请参阅http://learnyouahaskell.com/functors-applicative-functors-and-monoids