从monad转换为applicative

时间:2013-02-27 22:16:49

标签: haskell monads applicative

好的,所以我知道Applicative类型类包含什么,以及为什么它有用。但是我无法完全理解你如何在一个非平凡的例子中使用它。

例如,考虑以下相当简单的Parsec解析器:

integer :: Parser Integer
integer = do
  many1 space
  ds <- many1 digit
  return $ read ds

现在,如果不使用Monad Parser实例,你会怎么写?很多人声称这可以做到并且是个好主意,但我无法弄清楚究竟是怎么回事。

3 个答案:

答案 0 :(得分:39)

我写了

integer :: Parser Integer
integer = read <$ many1 space <*> many1 digit

有一堆左关联(如应用程序)解析器构建运算符<$><*><$<*。最左边的东西应该是纯函数,它从组件值组装结果值。每个运算符右侧的东西应该是一个解析器,从左到右共同给出语法的组成部分。使用哪个运算符取决于两个选项,如下所示。

  the thing to the right is    signal  / noise
  _________________________            
  the thing to the left is \           
                            +-------------------
                    pure /  |   <$>       <$
                  a parser  |   <*>       <*

因此,选择read :: String -> Integer作为将传递解析器语义的纯函数,我们可以将前导空间分类为&#34; noise&#34;和一堆数字为&#34;信号&#34;,因此

 read <$ many1 space <*> many1 digit
 (..)    (.........)     (.........)
 pure    noise parser     |
 (.................)      |
     parser              signal parser
 (.................................)
                    parser

您可以将多种可能性与

结合起来
p1 <|> ... <|> pn

并且

表示不可能
empty

很少需要在解析器中命名组件,结果代码看起来更像是带有语义添加的语法。

答案 1 :(得分:11)

integer :: Parser Integer
integer = read <$> (many1 space *> many1 digit)

或者

integer = const read <$> many1 space <*> many1 digit

您是否认为其中任何一个更具可读性取决于您。

答案 2 :(得分:8)

您的示例可以逐步重写为更明显类似于Applicative的表单:

do
  many1 space
  ds <- many1 digit
  return $ read ds
  1. do表示法的定义:

    many1 space >> (many1 digit >>= \ds -> return $ read ds)
    
  2. $的定义:

    many1 space >> (many1 digit >>= \ds -> return (read ds))
    
  3. .的定义:

    many1 space >> (many1 digit >>= (return . read))
    
  4. 第3个monad法律(结社):

    (many1 space >> many1 digit) >>= (return . read)
    
  5. liftM的定义(非do表示法):

    liftM read (many1 space >> many1 digit)
    
  6. 这是(或者应该是,如果我没有搞砸:))与你的例子相同的行为。

    现在,如果您将liftM替换为fmap <$>,将>>替换为*>,则会获得申请:

    read <$> (many1 space *> many1 digit)
    

    这是有效的,因为liftMfmap<$>通常应该是同义词,>>*>也是如此。

    这一切都有效,我们可以这样做,因为原始示例没有使用任何解析器的结果来构建以下解析器。

相关问题