4

我正在尝试在 Haskell 中实现组合逻辑,并且我想为该语言编写解析器。我无法让解析器通过 Parsec 工作。基本问题是我需要一种方法来确保解析器返回的对象类型正确。有没有人对如何做到这一点有任何创造性的想法?

{-# Language GeneralizedNewtypeDeriving #-}

import qualified Data.Map as Map
import qualified Text.ParserCombinators.Parsec as P
import Text.Parsec.Token (parens)
import Text.ParserCombinators.Parsec ((<|>))
import Control.Applicative ((<$>), (<*>), (*>), (<*))


data CTree = CApp CTree CTree | CNode String deriving (Eq, Read)
instance Show CTree where
    show c@(CApp x y) = showL c
        where showL (CApp x' y')= "(" ++ showL x' ++ " " ++ showR y' ++ ")"
              showL (CNode s) = s
              showR (CApp x' y') = "(" ++ showL x' ++ " " ++ showR y' ++ ")"
              showR (CNode s) = s

    show (CNode s) = s

-- | Parser
parseC :: String -> Maybe CTree
parseC s = extract$ P.parse expr "combinator_string" s
           where extract (Right r) = Just r
                 extract (Left e) = Nothing


expr :: P.CharParser () CTree
expr = P.try (CApp <$> (CApp <$> term <*> term) <*> expr)
       <|> P.try (CApp <$> term <*> term)
       <|> term


term = P.spaces *> (node <|> P.string "(" *> expr <* P.string ")")


node :: P.CharParser () CTree
node = CNode <$> (P.many1 $ P.noneOf "() ") 

eval (CApp (CNode "I") x) = x
eval (CApp (CApp (CApp (CNode "S") f) g) x) = 
    (CApp (CApp f x) (CApp g x))
eval (CApp (CApp (CApp (CNode "B") f) g) x) = 
    (CApp f (CApp g x))
eval (CApp (CApp (CApp (CNode "C") f) g) x) = 
    (CApp (CApp f x) g)
eval x = x
4

1 回答 1

3

我强烈主张解析为单一类型的表示,然后应用类型检查/精化阶段将其转换为类型化 (GADT) 表示。关于一般思想的最佳教程可能来自Lennart Augustsson 的基于 llvm 的编译器

SKI 演算的表示可能看起来像

data TyComb t where
  TyS   :: TyComb ((a -> b -> c) -> (a -> b) -> a -> c)
  TyK   :: TyComb (a -> b -> a)
  TyI   :: TyComb (a -> a)
  TyApp :: TyComb (a -> b) -> TyComb a -> TyComb b

evalTyComb :: TyComb t -> t
evalTyComb TyS         = \x y z -> (x z) (y z)
evalTyComb TyK         = const
evalTyComb TyI         = id
evalTyComb (TyApp a b) = (evalTyComb a) (evalTyComb b)
于 2012-10-18T03:15:46.657 回答