1

I Wonder if there is a better way (cause I'm feeling this is kinda "bad style") to store/alter values in Haskell:

foo :: IO ()
foo = do

  var <- return 3
  var <- if (...)
              then
                return (var + 3)
         else
           return (var - 3)

  (...)

  return ()
2
  • 2
    Actually you do not alter variables at all, you create a new variable with a closer scope, but this would fail dramatically for loops. Commented Mar 25, 2018 at 10:32
  • 2
    let var = if (...) then 6 else 0...? If that's not satisfactory, you should maybe modify your motivating example to show why. Commented Mar 25, 2018 at 12:12

1 Answer 1

5

The correct way to deal with changing variables in Haskell is with functions and recursion. To “change” the value of a variable you compute the new value and call some function with it. Then the function called will get that new value as it’s argument. Often this is a recursive call. Example with factorial below.

Imperative Pseudocode:

def factorial(n)
  a=1
  for i = 1 to n
    a = a*i
  return a

Translated to Haskell:

factorial n = go 1 1 where
  go a i | i <= n = go (a*i) (i+1)
  go a i | i >  n = a

Notice that we replace the mutation of variables with a recursive call. Here is factorial in idiomatic Haskell:

factorial n = product [1..n]

Often one doesn’t really need values of variables to change at all.

Finally one should note that you aren’t actually changing the value of the variable var because your code is doing something like:

return 3 >>= \var ->
(... return (var +3)) >>= \var ->
..,

So you’re just doing what I described above in a very roundabout unidiomatic way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.