Reputation: 91
Is there any 'elegant' way to use Bool type in numerical expressions ?
My current solution is using fromIntegral.fromEnum
but is seems long.
Example:
lst::[(Double, Double)]
lst = [(1, -1 * (odd i)) | i<- [1..]]
Upvotes: 0
Views: 160
Reputation: 14329
I do not understand the general purpose of interpreting Bools as Integers from the question, so I am only answering to the example given. Let me know how I can expand my answer.
lst::[(Double, Double)]
lst = [(1, -1 * (odd i)) | i<- [1..]]
The first element of the tuple is always 1, so this example can be simplified.
lst :: [Double]
lst = [-1 * (odd i) | i<- [1..]]
For the reader, odd :: Integral a => a -> Bool
, and fromEnum True = 1; fromEnum False = 0
.
Under the fromEnum
interpretation, lst
is an infinite list of -1
interspersed with zeroes. How else can we implement this list?
intersperse 0 (repeat (-1))
Then how do we get back the desired tuples? Apply fmap (1,)
to the list.
Upvotes: 1
Reputation: 48591
I don't believe there's a standard way. You can write your own, of course:
enumToNum :: (Enum e, Num n) => e -> n
enumToNum = fromIntegral . fromEnum
The existence of this and similar functions really points to the silly nature of the Enum
class.
Upvotes: 1
Reputation:
Package Foreign.Marshal.Utils
contains fromBool
function with the following definition:
-- |Convert a Haskell 'Bool' to its numeric representation
--
fromBool :: Num a => Bool -> a
fromBool False = 0
fromBool True = 1
While I don't recommend to import this package for fromBool
alone, you can copy it into your code.
By the way, good way to discover functions by type in the standard library is Hoogle.
Upvotes: 1