Haskell language injection: uniform lists

I am trying to create an interpreter for a functional language in haskell (I am new to the language). I am creating, perhaps, a strange combination of minimalism and convenience - no abstract data types, but I want to provide the ability to create uniform lists.

So my main variables are data Datum = DatInt Int | DatDbl Double | DatBool Bool data Datum = DatInt Int | DatDbl Double | DatBool Bool data Datum = DatInt Int | DatDbl Double | DatBool Bool , and I realized that I'm not at all sure how to present homogeneous lists. Adding a List Datum constructor or something like that would make a heterogeneous list, and create a separate list for each type, i.e. ListInt [Int] | ListDbl [Double] ListInt [Int] | ListDbl [Double] , would exclude lists of lists.

What would be the best way to present a uniform list?

+5
source share
1 answer

One useful concept (whether you are going for sex types or not) is a type tag. The non-sexy version is much easier to handle.

 data Tag = IntTag | DoubleTag | BoolTag | ListTag Tag deriving (Eq, Show) 

Your types are now represented by these various tags. An Int appears to be IntTag . The Int List is represented by the ListTag IntTag .

Now you can imagine annotated expressions like this:

 data Expr = IntLit Int | DoubleLit Double | BoolLit Bool | ListLit Tag [Expr] -- Check that an expression is validly annotated typeCheck :: Expr -> Maybe Tag typeCheck IntLit{} = Just IntTag ... typeCheck (ListLit tag els) | all good els = Just (ListTag tag) | otherwise = Nothing where good el = case typeCheck el of Nothing -> False Just res = res == tag 
+5
source

Source: https://habr.com/ru/post/1238581/


All Articles