Reputation: 3247
I need to create an empty list of specific type.
I am creating a stack which in internally a list. To create empty stack I need to pass empty list. But how can I pass a empty list of specific type.
data Stack' a = Stack' [a] deriving (Show)
main = print("MyName", " ", Stack' Int [])
Instead of Int []
, I have tried []::Int
and various other combination with brackets. But no success. Currently I have settled with
ls :: [Int]
ls = []
Stack' ls
Upvotes: 3
Views: 1924
Reputation: 476624
You can set the type after double colons (::
), like:
main = print ("MyName", " ", Stack' [] :: Stack' Int)
here we thus set that the type of the third parameter of the 3-tuple is an object with type Stack' Int
.
or here you can also set the type at the list level (but these are equivalent):
main = print ("MyName", " ", Stack' ([] :: [Int]))
or more canonical:
main = print ("MyName", " ", Stack' ([] :: [] Int))
Here we thus specify "An empty list of type [Int]
".
Note that this will print a the value with the parenthesis and commas of the 3-tuple:
Prelude> print ("MyName", " ", Stack' [] :: Stack' Int)
("MyName"," ",Stack' [])
If you want to print this without the "3-tuple noise", you should construct a string, for example by using show :: Show a => a -> String
:
main = putStrLn ("MyName " ++ show (Stack' [] :: Stack' Int))
This then yields:
Prelude> putStrLn ("MyName " ++ show (Stack' [] :: Stack' Int))
MyName Stack' []
We can also make use of a GHC extension: TypeApplication
.
In that case we need to compile with the -XTypeApplication
flag, or write {-# LANGUAGE TypeApplication #-}
in the head of the file.
We can then specify the type of the type parameter a
with the @Type
notation, like:
main = print ("MyName", " ", Stack' @Int [])
Upvotes: 6