3

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
0

1 Answer 1

6

Specifying an explicit type

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' []

Type applications

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 [])
Sign up to request clarification or add additional context in comments.

2 Comments

There's also the type-application option Stack' ([] @Int).
Ooh, that's better anyway. I didn't think to apply Stack' itself to @Int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.