Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning multiple variables in Haskell

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.

like image 917
alexp Avatar asked Jan 25 '15 17:01

alexp


1 Answers

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.

like image 138
dfeuer Avatar answered Sep 23 '22 14:09

dfeuer