How to access the list item that I added using the cons (:) operator?

I'm new to Haskell (and in general functional programming) and wondered how I can access the new item that I added to the list using the cons (:) operator?

For example, using WinGHCi , I create a new list and access the first item:

ghci> let a = [1,2,3] ghci> a!!0 1 

The prompt returns 1, the value of the first element, cool. Now I add a new value to the top of the list and try to access it:

 ghci> 5:a [5,1,2,3] ghci> a!!0 1 

It seems that list items are not reinstalled. I tried to get a negative index to work and other similar things, but the compiler did not seem to approve. The textbooks that I read just slip through it, and I could not find anything on the Internet. How to get the value "5" from the list?

Thanks for the help and sorry if this is a very simple question.

+7
source share
4 answers

This idea underlies functional programming: you (usually) do not modify data in place. Thus, you do not add an item to the list: you create a new list without changing the old one.

This allows a lot of nice things, such as sharing, as you never change old data and therefore can continue to reference it. But it also puts a strain if you are used to other programming paradigms: you need to change your approach to things (and often you have to change your data structures / algorithms because they rely on modifying the data structure in place).

In your example, just specify a new name in the cons'ed list:

 let a = [1, 2, 3] let b = 5:a 
+12
source

Your misunderstanding is fundamental: cons do not destroy anything.

5:a (where a = [1,2,3] ) is evaluated to [5,1,2,3] , and this is what the interpreter shows you.

+7
source

Let me illustrate (+) as well (:)

 Prelude> 4+5 9 Prelude> let z = 5 Prelude> z 5 Prelude> 4+z 9 Prelude> z 5 Prelude> let y = 4+z Prelude> y 9 Prelude> z 5 

against

 Prelude> let a = [1,2,3] Prelude> a [1,2,3] Prelude> 5:a [5,1,2,3] Prelude> a [1,2,3] Prelude> let b = 5:a Prelude> b [5,1,2,3] Prelude> a [1,2,3] 

The bindings made with "let" never change, but new ones can be made. If the new binding has the same name as the old binding, then the old binding is “shadowed”, not mutated.

+6
source

Lists are immutable:

 Prelude> let xs = [1,2,3] Prelude> 4:xs [4,1,2,3] Prelude> xs [1,2,3] Prelude> let ys = 4:xs Prelude> ys [4,1,2,3] 

If you want to modify data structure elements, use Arrays .

+2
source

All Articles