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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With