I’m trying to make a simple Scheme interpreter in Haskell. As part of this, I’m implementing some primitive operators like number?, string? etc.
I have code like this:
isNumber :: [LispVal] -> LispVal
isNumber ([Number n]) = Bool True
isNumber _ = Bool False
isString :: [LispVal] -> LispVal
isString ([String n]) = Bool True
isString _ = Bool False
And what I’d like is something like
isType :: ?? -> [LispVal] -> LispVal
isType (typeName [typeName n]) = Bool True
isType _ = Bool False
In other words, I’d like to create the equivalent of isNumber by saying “isType Number”. Is this possible somehow? I’m struggling to find anything similar in Google, maybe because I don’t know what to call the situation.
I’m assuming you have a type something like this:
…and you want a function that tests whether a
LispValvalue is a particular constructor (String,Number, &c.) based on some argument.There’s not really a straightforward, generic way to do this, unfortunately.
You could resort to string comparisons:
Or you could compare the types of two
LispVals:…and then create a dummy value to compare with for
isType.You could also make a “type” value and implement a sort of reflection on
LispVals, then compare based on those:Some variation on one of these approaches is probably your best option. There are other ways, based on more advanced features of Haskell, but they’re probably not worth the hassle unless the interpreted language’s types tie much more closely to Haskell’s types.