I'm new to Haskell (and functional programming in general) and was wondering how I can access a new element that I've added to a list using the cons (:) operator?
For example, using WinGHCi I create a new list and access the first element:
ghci> let a = [1,2,3]
ghci> a!!0
1
The prompt returns 1, the value of the first element, cool. Now I append a new value to the front of the list and try to access it:
ghci> 5:a
[5,1,2,3]
ghci> a!!0
1
It looks like the list items don't get re-indexed. I tried getting a negative index to work and other such things but the compiler didn't seem to approve. The tutorials I'm reading just skip over it and I couldn't find anything of use online. How do I get the value "5" from the list?
Thanks for the help and sorry if this is a very basic question.
Example #1print("Demo to show list in Haskell !!") let list1 = [100, 50, 235, 167, 345, 909, 675, 20] let list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9] let list3 = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6] let list4 = [5, 10, 15, 20, 15, 30, 35, 40] let list5 = [123.4, 567.9, 56.0, 3.9, 76.9] print("printing list element !!")
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.
This idea lies at the core of functional programming: you are (usually) not modifying data in place. So you don't add an item to a list: you create a new list without modifying the old one.
This allows for many nice things, sharing for instance, because you are never changing the old data and so you can keep referring to it. But it also imposes a burden if you are accustomed to other programming paradigms: you have to change your way to approach things (and often you have to change your data structures/algorithms because they were relying on in-place modification of a data structure).
In your example, just give a new name to the cons'ed list:
let a = [1, 2, 3]
let b = 5:a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With