Getting an error: parse error on input ‘Just’

Getting an error: parse error on input ‘Just’

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’时出现解析错误 “

我做错了什么?

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

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

的顺序

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

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),第二个参数是查找 table 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 模式,我们应该 return 那 Type.

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