Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 这是如何得到正确答案的::a b->;也许b工作?_Haskell_Pattern Matching_Do Notation - Fatal编程技术网

Haskell 这是如何得到正确答案的::a b->;也许b工作?

Haskell 这是如何得到正确答案的::a b->;也许b工作?,haskell,pattern-matching,do-notation,Haskell,Pattern Matching,Do Notation,在“有用的应用程序”部分,我发现: 应该提到的是,do有时会从您身上卸下负担 写无聊的东西 例如在 getRight :: Either a b -> Maybe b getRight y = do Right x <- y return x 这给了我一个语法错误“parse error on input`}”。我不明白为什么这不起作用,但让我们用多行符号来写: getRight y = do let (Right x) = y return x

在“有用的应用程序”部分,我发现:

应该提到的是,do有时会从您身上卸下负担 写无聊的东西

例如在

getRight :: Either a b -> Maybe b
getRight y =
   do Right x <- y
      return x
这给了我一个语法错误“parse error on input`}”。我不明白为什么这不起作用,但让我们用多行符号来写:

getRight y = do
    let (Right x) = y
    return x
啊,这似乎奏效了——至少是解析。然而:

*Main> getRight (Right 5)
Just 5
*Main> getRight (Left 5)
Just *** Exception: […]\test.hs:16:13-25: Irrefutable pattern failed for pattern (Data.Either.Right x)
-- `Nothing` was expected
有什么好处?所以我现在的问题是:

  • 这里发生了什么事?为什么分号括号行不起作用
  • 如何正确操作(使用
    do
    ,其他一切都是琐碎的)

    • 这个例子可能是

      getRight :: Either a b -> Maybe b
      getRight y =
         do Right x <- return y -- note: return = Just
            return x
      

      FWIW大多数有经验的人似乎认为
      失败
      作为
      单子
      方法是一个缺点。查看一个可能更有原则的失败方法。

      该页面通常存在一些问题。。。例如,整个段落都过时了,脚注中说它们过时了(为什么不删除它呢?)。因此,只有
      getRight上的解析错误是因为通常情况下,一旦切换到显式大括号和分号,然后嵌套在里面的所有语言构造也必须使用显式大括号和分号:
      getRight y=do{let{Right x=y};return x}
      @kosmikus:Hm,这样我就得到了一个“输入解析错误”`=”,不知道。使用ghc-7.4.2、ghc-7.6.3和ghc-7.8.1-rc1对我有效…@kosmikus:嗯,没关系。完全是初学者的错误:我忘记了ghci中的第一个
      let
      getRight :: Either a b -> Maybe b
      getRight y =
         do Right x <- return y -- note: return = Just
            return x
      
      getRight y = let ok (Right x) = do {return x}
                       ok _         = fail "pattern mismatch error"
                   in return y >>= ok