Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Treating Bool as Int

Tags:

haskell

How would one implement a function that started with an int, and subtracted 1 from it for every time (going through a finite number of possibilities) one of several (for example, 5) boolean values returned 1.

How this would ideally look look is:

function list1 list2 = num
  where
      num = 4
          - (condition from var1 = true)
          - (condition from var2 = true)
          - (so on, so forth as long as needed)

I have tried implementing these lines similarly to:

      num = startVal
          - (list1conditional == desiredVal)
          - (etc)

But this is returning type errors.

like image 824
Gabriel Vega Avatar asked Sep 05 '18 12:09

Gabriel Vega


1 Answers

Bool is an instance of Enum: you can enumerate the two values of a Bool: False, and then True.

As a result, it implements the fromEnum :: Enum a => a -> Int, a function that maps a value of an Enum type to an Int: for a Bool, it maps False to 0, and True to 1.

So we can use this like:

result = 5 - fromEnum cond1 - fromEnum cond2

Or for example with a list of conditions:

result = 5 - sum (map fromEnum [cond1, cond2, cond3])

where cond1 and cond2, etc. are expressions of type Bool.

like image 120
Willem Van Onsem Avatar answered Oct 06 '22 08:10

Willem Van Onsem