Assigning Multiple Variables in Haskell

Just get started with Haskell, and I'm trying to find a better way to assign multiple variables based on one condition. Until now, I just packed and unpacked tuples. Is there a better / more idiomatic way?

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

Also interested in the cost of packaging and unpacking tuples. If I read this correctly, it looks like it is being optimized in functions, but not sure if this is the case with the assignment.

+5
source share
1 answer

Yes, that's great. If you compile with optimizations enabled, the tuples will be truly “unpacked”, so they will not have additional costs. The code will be transformed into something like this:

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

Unboxed 3-tuple is actually only three values ​​- it has no extra structure. As a result, it cannot be stored in the data structure, but this is normal. Of course, if foo known at compile time, case will also be optimized, and you will only get three definitions.

+6
source

Source: https://habr.com/ru/post/1211886/


All Articles