键入的表达式解析器

时间:2013-02-26 09:14:28

标签: haskell

我正在尝试在Haskell中创建一个类型化的表达式解析器,到目前为止效果很好,但我目前正在努力实现更高阶的函数。我把这个问题简化为一个简单的例子:

{-# LANGUAGE TypeFamilies,GADTs,FlexibleContexts,RankNTypes #-}

-- A function has an argument type and a result type
class Fun f where
  type FunArg f
  type FunRes f

-- Expressions are either constants of function applications
data Expr a where
  Const :: a -> Expr a
  App :: Fun f => f -> FunArg f -> Expr (FunRes f)

-- A very simple function
data Plus = Plus

-- Which takes two integer expressions and returns an integer expression
instance Fun Plus where
  type FunArg Plus = (Expr Int,Expr Int)
  type FunRes Plus = Int

-- A more complicated function which lifts a function to lists (like in haskell)
data Map f r = Map f

-- For this we need the concept of lifting function arguments:
class Liftable a where
  type LiftRes a

-- A singleton argument is lifted by changing the expression type from a to [a]
instance Liftable (Expr a) where
  type LiftRes (Expr a) = Expr [a]

-- Two function arguments are lifted by lifting each argument
instance (Liftable a,Liftable b) => Liftable (a,b)  where
  type LiftRes (a,b) = (LiftRes a,LiftRes b)

-- Now we can declare a function instance for Map
instance (Fun f,Liftable (FunArg f),r ~ LiftRes (FunArg f)) => Fun (Map f r) where
  type FunArg (Map f r) = r
  type FunRes (Map f r) = [FunRes f]

-- Now a parser for functions:
parseFun :: [String] -> (forall f. Fun f => f -> a) -> a
-- The parser for the plus function is easy:
parseFun ["plus"] f = f Plus
-- But the parser for map is not possible:
parseFun ("map":sym) f 
  = parseFun sym (\fun -> f (Map fun))

问题似乎是没有办法说服类型检查器每个LiftRes本身都是Liftable,因为禁止递归类声明。

我的问题是:我如何使这项工作?是否有其他类型化表达式解析器的示例,我可以从中获取提示?

编辑:似乎this discussion about type family constraints似乎非常相关。但是,我没有让他的解决方案适用于我的情况,也许有人可以帮忙解决这个问题?

1 个答案:

答案 0 :(得分:4)

使示例工作的最简单方法是从实例声明中删除Liftable (FunArg f)约束。但我认为你的例子是如此浓缩,以至于它没有说明你实际需要它的原因。

所以接下来最好的事情是在Liftable (FunArg f)类中添加Fun超类约束:

class Liftable (FunArg f) => Fun f where
  ...

如果这不可行(即,如果不是所有函数都具有可升级的参数类型),那么您不能期望写出给定类型的parseFun

更一般的评论:我认为你在这里尝试做的事情很奇怪,也许一下子太多了。从非结构化字符串解析为无上下文数据类型已经足够困难了。为什么不首先这样做,并编写一个单独的函数,将您的语言的“无类型”但结构化的表示转换为键入的语言。

编辑(作为对评论的反应,已修订):正如the discussion on type family constraints中指出的那样,您也在问题中进行了链接,您可以使用{{{{}}绕过超类循环限制1}}。这是一种让简化示例工作的方法。也许这会扩展到完整的解决方案?

ConstraintKinds
相关问题