获取错误:解析输入'Just'时出错

时间:2018-04-07 20:30:01

标签: haskell functional-programming haskell-platform

data Type = Nat | Bool | App Type Type | Var String 
     deriving (Eq, Show)

type Substitution = [(String, Type)]

apply :: Substitution -> Type -> Type
apply s Nat = Nat
apply s Bool = Bool
apply s Var c = case (lookup s c) of 
                Nothing -> (Var c)
                Just v  ->  v

但编译器给我错误“错误:输入解析错误'Just' “

我做错了什么?

2 个答案:

答案 0 :(得分:3)

我无法在本地重现错误,所以我的猜测是你使用了制表符空格,但是如果你复制粘贴代码到编辑器中,它应该“工作”。在这种情况下,我们会收到另一个错误:

GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( tmp.hs, interpreted )

tmp.hs:7:1: error:
    Equations for ‘apply’ have different numbers of arguments
      tmp.hs:7:1-17
      tmp.hs:(9,1)-(11,29)
Failed, modules loaded: none.

这是因为你写了:

apply s Var c = -- ...

和Haskell假设您在这里写了三个参数:sVarc,但c当然属于Var数据构造函数。我们可以用一对括号来解决这个问题。此外,您以错误的方式调用lookuplookup具有类型lookup :: Eq a => a -> [(a, b)] -> Maybe b,因此第一个参数是键(此处为c),第二个参数是查找表s。所以我们可以用以下方法解决这个问题:

apply :: Substitution -> Type -> Type
apply s Nat = Nat
apply s Bool = Bool
apply s (Var c) = case (lookup c s) of 
    Nothing -> (Var c)
    Just v  ->  v

请注意,您可以摆脱case模式匹配,并使用例如fromMaybe :: a -> Maybe a -> a代替:

import Data.Maybe(fromMaybe)

apply :: Substitution -> Type -> Type
apply s Nat = Nat
apply s Bool = Bool
apply s d@(Var c) = fromMaybe d (lookup c s)

我们可以进一步将NatBool案例分组在一起:

import Data.Maybe(fromMaybe)

apply :: Substitution -> Type -> Type
apply s d@(Var c) = fromMaybe d (lookup c s)
apply s t = t

当然,如果Type Var c模式,我们应该返回Type

也许你需要递归地调用apply,因为替换可以导致另一个Var(因此你必须做额外的查找)。但是这将在语义上改变函数(!),所以我不确定这是否是一个要求。

答案 1 :(得分:1)

我收到有关要应用的args数量和查找类型的错误,但是此代码类似于:

data Type = Nat | Bool | App Type Type | Var String
    deriving (Eq, Show)

type Substitution = [(String, Type)]

apply :: Substitution -> Type -> Type
apply s Nat = Nat
apply s Bool = Bool
apply s (Var c) = case (lookup c s) of
    Nothing -> (Var c)
    Just v -> v

请注意Var c周围的括号和lookup c s

的顺序