Haskell: all the names in Haskell are immutable? No difference between table and list?

advertisements

I have two questions:

  1. In FP langauges like scala or F#, there are keywords to identify whether a variable is mutable or not. When we say Haskell is a pure FP language, everything is "immutable"?

  2. Scala based on jvm, F# based on .net, both differentiate between "Array" and "List". Does Haskell tells this different, or every container in Haskell is a "list" or "tuple"?


In Haskell, all variables are immutable. However, there are various special data structures that support mutation. For a start, you can read and write files in Haskell, and you could consider a file as a giant mutable variable. But of course, Haskell also supports in-memory mutable structures (IORef, STRef, MVar, TVar, etc.) So (for example) the variable x always points to the same IORef object, but the contents of that object can be changed.

Mutating stuff is considered a side-effect, which in Haskell is controlled via monads. If a function's type signature doesn't mention IO, then you can't perform any I/O operations. That includes mutating in-memory data that other threads can see. (But, interestingly, doesn't include mutating data only visible to this function. So you can do mutation inside a pure function, so long as there are no externally visible effects of this.)

Haskell "defaults to" immutable single-linked lists, but also supports both immutable and mutable arrays. Modifying an immutable array requires copying the entire array, turning update in to an O(n) operation, and thus destroying a key advantage of arrays. Immutable arrays still make an excellent look-up table for constant data, but most array-based algorithms want mutable arrays, which is why those are also provided.