简体   繁体   中英

Haskell: Treating Bool as Int

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM