I am trying to set up a data structure that is an extension of lambda calculus to allow addition and subtraction. I am trying to create a structure called AE that can either have a Lit as itself, or evaluate addition and subtraction. The error I am getting says that the following:
Invalid type signature: Lit:: ...
Should be of form variable:: type
Lit:: 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:
{-# 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. If it is indented, then it is part of the data AE where
block, and you thus define three data constructors.
Your eval
function also contains a do
block. Although Maybe
is an instance of Monad
, you can not use do
notation like that. Especially the return nothing
part is problematic here. For the Monad
instance Maybe
, return = Just
, so that means that return Nothing
would construct a Maybe (Maybe a)
. You can work with guards to define conditions when a guard should "fire".
Another problem is n1 + n2
. This has type Int
, not Maybe Int
, so you need to wrap it into a Just
data constructor:
eval :: AE -> Maybe Int
eval (Lit n) = Just n
eval (Add n1 n2) = Just (n1 + n2)
eval (Sub n1 n2)
| = Nothing
| = Just (n1 - n2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.