3 ms·
> If we look to a language like Haskell we see that reassigning variables, in general, is frowned upon (is it even possible?) This is perfectly valid Haskell:
by runeks 9y ago
> If we look to a language like Haskell we see that reassigning variables, in general, is frowned upon (is it even possible?)
This is perfectly valid Haskell:
main = do
let a = 7
print a
let a = 9
print a
but you'll get a warning for it: tmp.hs:4:7: warning: This binding for ‘a’ shadows the existing binding bound at tmp.hs:2:7
- weinzierl 9y agoThe warning says it right away, the first a is shadowed, not reassigned, here. The difference is that when a is reassigned the 7 is lost, while it should be still around when shadowed. I don‘t know of a way to access the 7 in this example however.
- runeks 9y agoIf there’s no way to access the 7 after it’s shadowed, why couldn’t an optimized garbage collector throw it away after it’s shadowed, thus making it equivalent to reassignment?
- maxxxxx 9y agoWhy would they allow this? Is there any legitimate case where doing this makes sense? Seems very risky to me. In most languages I know you would expect that the "a" variables are the same.
- christophilus 9y agoIn the past, I've used it in order to ensure the variable has a legitimate value. So, something like this (pseudo code): fn foo(a): a = a |> trim |> (default "chocolate") mix a "milk" Well, in this contrived example, I wouldn't reassign a, just tack on `|> (mix "milk")` but in a complex example where you're reusing `a` in several places, it can make sense and is nicer than having to declare a bunch of variables just to hold the sanitized values of arguments.
- maxxxxx 9y agoLooks like you are using it as a reassignable function argument. Makes sense.