1

I have 2 dummy functions. In function 2, I'm trying to set a parameter to a different value. In function 1, I copy the parameter value to a variable and then try to change the value of that variable.

In both case, I get the same error (Shown below). I may not understand what is the cause of the error, but it seems that I can't modify the value of a variable once set. If that's the case, why? And if it is for a different reason, what is it?

Function1

myFunction :: [Char] ->[Char] -> [Char]
myFunction a b = if length a > 1
                     then do
                         let a1 = a
                         a = a1 ++  "333"
                  else
                      b

Function2

myFunction :: [Char] ->[Char] -> [Char]
myFunction a b = if length a > 1 then a = "333" else b

Error

Stackoverflow.hs:8:28: error:
    parse error on input `='
    Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'
  |
8 |                          a = a1 ++  "333"
  |                            ^

Common main used for both function:

main :: IO ()
main = do
    putStrLn (myFunction "stack" "overflow")
vincedjango
  • 1,022
  • 1
  • 13
  • 24
  • 5
    Variables in Haskell are not "set" even once. They are *defined* (or, rather, bound) and cannot be redefined, reset, reassigned, or anything like that. – n. m. could be an AI Aug 31 '18 at 06:25
  • "If that's the case, why" the short explanation is that Haskell is a pure functional language. The long explanation would consist of a definition of "pure functional", but that would be *too* long. Fortunately you can look it up. – n. m. could be an AI Aug 31 '18 at 06:37
  • 1
    Oh and `do` doesn't really do what you think it does... – n. m. could be an AI Aug 31 '18 at 06:39
  • 6
    "Why?" -- it's like Haskell's whole thing. That and nice types. No changing things and types. That's what you get with your basic Haskell. Haskell doesn't want to be python, it wants to be Haskell. And so you can't change things. Oh and lazy. No changing things, don't do anything till you have to, and also types. Haskell. – luqui Aug 31 '18 at 06:40
  • 1
    [related](https://stackoverflow.com/questions/11922134/how-to-increment-a-variable-in-functional-programming). Instead of changing stuff we return an augmented copy, making the change explicit. As a hack, we can call the new thing by the old name, shadowing the old thing (making it inaccessible). It's easy esp. in `do` notation. Details in the linked entry. – Will Ness Aug 31 '18 at 06:55
  • 1
    I closed it as a duplicate. The question is a bit different, but the answers apply, I think. – Will Ness Aug 31 '18 at 07:07
  • 2
    Thanks, the answer you posted is exactly what I was looking for. – vincedjango Aug 31 '18 at 21:15
  • that's good to hear! :) – Will Ness Sep 02 '18 at 11:29

0 Answers0