FastBatteryCharger
FastBatteryCharger

Reputation: 349

Haskell, list will not save variables?

i got a small problem, i am very new to Haskell and i dont understand why the list is empty after appending 20.

*Main> list
[]
*Main> add_element
[20]
*Main> list
[]
*Main> 

my code:

list = []

add_element = list++[20]

Upvotes: 0

Views: 356

Answers (2)

Chad Gilbert
Chad Gilbert

Reputation: 36375

Values in Haskell are immutable. Your code simply defines an empty list value for list that will never change.

add_element is a value representing list with the integer value 20 appended onto the end. It did not, it cannot change the list value.

Take a look at some intro Haskell guides to get a feel for what immutability means.

Upvotes: 4

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

In Haskell variables are immutable. In your case:

list = []

You have defined an empty list.

add_element = list ++ [20]

The add_element symbol is not a function that mutates list. It is actually a new list built by combining the empty list (list) with the singleton list [20].

The top level definition list will never be anything besides [].

Upvotes: 8

Related Questions