Reputation: 3
I'm currently trying to write a code which requires concatenation of two lists. But I want to store this result into the first list (just like strcat() in C). Is there any way to do this ?
Upvotes: 0
Views: 86
Reputation: 1732
Yes, it is possible to do what you want. You need to create a mutable variable, such as a state variable, or use STM, and store the value in it.
However, this is not a good idea. For one thing, it is complicated. But more that that, it is better by far to accept the general design of Haskell as an immutable language, and use mutable data only when absolutely required.
The term 'immutable' means that once a variable is assigned then it doesn't change again. Immutable variables, more accurately called values
, have some important benefits. Some languages like F# and Rust have variables which are immutable by default, and you have to specify that the variable is mutable if you want it to be so. Haskell just takes it further.
A Haskell version of strcat
would look like this:
strcat :: String -> String -> String
strcat s1 s2 = s1 ++ s2
The values of s1
and s2
come in at the top, and the concatenated value comes out at the bottom, but only as an input for some other function. Nothing is stored. Functions in Haskell are better thought of as having data flowing through them.
Every language has its own idioms, and when you use the language things are easier if you stick to those idioms. What is true of a language like C or Python is doubly true of Haskell.
Upvotes: 2
Reputation: 10645
That is not possible, because all values are immutable in Haskell.
Upvotes: 0