【发布时间】:2012-10-25 09:01:55
【问题描述】:
有人可以帮助我了解如何使用 Applicative 样式来编写 Parsec 解析器吗?这是我的代码:
module Main where
import Control.Applicative hiding (many)
import Text.Parsec
import Data.Functor.Identity
data Cmd = A | B deriving (Show)
main = do
line <- getContents
putStrLn . show $ parseCmd line
parseCmd :: String -> Either ParseError String
parseCmd input = parse cmdParse "(parser)" input
cmdParse :: Parsec String () String
cmdParse = do
slash <- char '/'
whatever <- many alphaNum
return (slash:whatever)
cmdParse2 :: String -> Parsec String () String
cmdParse2 = (:) <$> (char '/') <*> many alphaNum
但是当我尝试编译它时,我得到以下信息:
/home/tomasherman/Desktop/funinthesun.hs:21:13:
Couldn't match expected type `Parsec String () String'
with actual type `[a0]'
Expected type: a0 -> [a0] -> Parsec String () String
Actual type: a0 -> [a0] -> [a0]
In the first argument of `(<$>)', namely `(:)'
In the first argument of `(<*>)', namely `(:) <$> (char '/')'
Failed, modules loaded: none.
我的想法是我希望 cmdParse2 做与 cmdParse 相同的事情,但是使用应用程序......我的方法可能完全错误,我是 haskell 的新手
【问题讨论】:
-
你的错误好像你写的是
(++) <$> ...而不是(:) <$> ...。 -
抱歉,已修复 .. 我正在尝试使用 ++ 和 : 并搞混了
-
经过深入研究的终极问题,因为答案是“做得好,选择正确,做得正确,但要修复这个小类型错误。” +1
标签: haskell functional-programming applicative