jhegedus
jhegedus

Reputation: 20653

What is the difference between 1:[ ] and [1]? How would you implement : and [ ] in Haskell?

What is : ? Is it an infix value constructor ?

What is its definition?

I cannot really find the source code for :.

Also, what is [ ] ?

Is [1] defined as a simple algebraic data type? If yes, how ?

Is it something like data [a] = a:[ ] | [ ] ?

This is just my guess. I'm not sure.

What is the source code for : and [ ]?

Are these constructs hard-coded into the compiler?

Let's call : as cons and [ ] as Nil. Using these names how would you implement the equivalent of : and [ ] in Haskell ?

Upvotes: 1

Views: 181

Answers (1)

Sibi
Sibi

Reputation: 48756

: is a List constructor function.

λ> :t (:)
(:) :: a -> [a] -> [a]
λ> 3 : [2,4]
[3,2,4]

1:[] and [1] are the same. In the first form, you have applied the function : to create [1].

[] is used to denote empty list. Another usage of [] is as a type constructor. This is used for creating instances of Applicative etc.

Actually, when you write something like [1,2,3], it is a syntactic sugar for 1:2:3:[].

Thanks to @ManuelEberl, you can find the source here.

You can create your own List using Cons and Nil like this:

data MyList a = Nil | Cons a (MyList a) deriving (Show)

It just takes a recursive structure to define it. Some demo:

λ> Cons 3 Nil
Cons 3 Nil
λ> Cons 3 (Cons 3 Nil)
Cons 3 (Cons 3 Nil)

Let me create a function named constructMyList which will resemble ::

constructMyList :: a -> MyList a -> MyList a
constructMyList x y = Cons x y 

It's demo:

λ> let a = Cons 2 (Cons 3 Nil)
λ> constructMyList 1 a
Cons 1 (Cons 2 (Cons 3 Nil))

Upvotes: 4

Related Questions