7

Just getting started in Haskell, and I'm trying to figure out the best way to assign multiple variables based on a single condition. So far I've just been packing and unpacking Tuples. Is there a better/more idiomatic way?

(var1, var2, var3) = 
    if foo > 0
        then ("Foo", "Bar", 3)
        else ("Bar", "Baz", 1)

Also curious about the cost of packing and unpacking the Tuples. If I'm reading this correctly, it seems like this gets optimized away in functions, but not sure if that's the case with an assignment.

2
  • 1
    You could use lists as well, just so you know. You could even pattern match it in greater chunks using (a:b:c:rest) = [1,2,3,4,5,6] where a = 1, b = 2, c = 3, and rest = [4,5,6]. Furthermore, this is only necessary in let and where statements, not in base expression level. Commented Jan 25, 2015 at 17:45
  • 9
    Since we do not have mutable variables in Haskell, we call these "bindings" or "definitions" rather than "assignments". Your code looks fine, and I wouldn't worry about the cost unless profiling points at it. Also, if you worry about this tuple, you don't want to know how "Bar" is actually represented at runtime... ;-) Commented Jan 25, 2015 at 17:46

1 Answer 1

6

Yes, that's perfectly fine. If you compile with optimizations enabled, the tuples will indeed by "unboxed", so they incur no extra cost. The code will be transformed to something vaguely like this:

(# var1, var2, var3 #) = 
    case foo > 0 of
        False -> (# "Bar", "Baz", 1 #)
        True -> (# "Foo", "Bar", 3 #)

An unboxed 3-tuple is actually just three values—it doesn't have any sort of extra structure. As a result, it can't be stored in a data structure, but that's okay. Of course, if foo is known at compile time, the case will be optimized away too, and you'll just get three definitions.

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.