简体   繁体   English

Haskell 数据结构未加载

[英]Haskell Data Structure not loading

I am trying to set up a data structure that is an extension of lambda calculus to allow addition and subtraction.我正在尝试设置一个数据结构,它是 lambda 微积分的扩展,以允许加法和减法。 I am trying to create a structure called AE that can either have a Lit as itself, or evaluate addition and subtraction.我正在尝试创建一个名为 AE 的结构,它可以将 Lit 作为自身,也可以评估加法和减法。 The error I am getting says that the following:我得到的错误说明如下:

Invalid type signature: Lit:: ...无效的类型签名:Lit:: ...

Should be of form variable:: type应该是形式 variable:: type

Lit:: Int -> AE点亮:: Int -> AE

What is wrong with my declartion of this data structure?我对这个数据结构的声明有什么问题?

{-# Language GADTs #-}
data AE where
Lit :: Int -> AE
Add :: Int -> Int ->  AE
Sub :: Int -> Int ->  AE

deriving (Show)


eval  ::  AE ->  Maybe Int
eval (Lit n) = Just n
eval (Add n1 n2) = n1 + n2
eval (Sub n1 n2) = do
                      if(n1<n2) then return nothing
                      else return n1 - n2

You need to indent the data constructors under the where clause, so:您需要在where子句下缩进数据构造函数,因此:

{-# Language GADTs #-}

data AE where
    Lit :: Int -> AE
    Add :: Int -> Int -> AE
    Sub :: Int -> Int -> AE

otherwise, you are defining a type AE without any data constructors.否则,您将定义一个没有任何数据构造函数的AE类型。 If it is indented, then it is part of the data AE where block, and you thus define three data constructors.如果它是缩进的,那么它是data AE where块的一部分,因此您定义了三个数据构造函数。

Your eval function also contains a do block.您的eval function 还包含一个do块。 Although Maybe is an instance of Monad , you can not use do notation like that.虽然MaybeMonad的一个实例,但你不能像那样使用do表示法。 Especially the return nothing part is problematic here.尤其是return nothing部分在这里是有问题的。 For the Monad instance Maybe , return = Just , so that means that return Nothing would construct a Maybe (Maybe a) .对于Monad实例Maybereturn = Just ,这意味着return Nothing将构造一个Maybe (Maybe a) You can work with guards to define conditions when a guard should "fire".您可以与警卫一起定义警卫应该“开火”的条件。

Another problem is n1 + n2 .另一个问题是n1 + n2 This has type Int , not Maybe Int , so you need to wrap it into a Just data constructor:这具有类型Int ,而不是Maybe Int ,因此您需要将其包装到Just数据构造函数中:

eval :: AE ->  Maybe Int
eval (Lit n) = Just n
eval (Add n1 n2) = Just (n1 + n2)
eval (Sub n1 n2)
    | n1 < n2 = Nothing
    | otherwise = Just (n1 - n2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM