简体   繁体   English

Haskell:将Bool视为Int

[英]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. 如何实现一个以int开头的函数,并且每次从它中减去1(通过有限数量的可能性),其中一个(例如,5个)布尔值返回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 . BoolEnum一个实例:你可以枚举Bool的两个值: False ,然后是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 . 其结果是,它实现了fromEnum :: Enum a => a -> Int ,一个映射的值的函数Enum类型的Int :用于Bool ,它映射False0 ,并True1

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 . 其中cond1cond2等是Bool类型的表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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