Skip to content

Instantly share code, notes, and snippets.

@pbrisbin
Created April 4, 2011 18:35
Show Gist options
  • Select an option

  • Save pbrisbin/902143 to your computer and use it in GitHub Desktop.

Select an option

Save pbrisbin/902143 to your computer and use it in GitHub Desktop.
Does something like this already exist?
module Data.Boolish (Boolish(..)) where
-- | Class for boolean-like datastructures
class Boolish a where
isTrue :: a -> Bool
-- | Default binding is @'not' . 'isTrue'@
isFalse :: a -> Bool
isFalse = not . isTrue
instance Boolish Bool where
isTrue True = True
isTrue _ = False
-- * Numerics
instance Boolish Int where
isTrue 0 = False
isTrue _ = True
instance Boolish Integer where
isTrue 0 = False
isTrue _ = True
instance Boolish Float where
isTrue 0 = False
isTrue _ = True
instance Boolish Double where
isTrue 0 = False
isTrue _ = True
-- * Lists
-- | Only the empty list is 'False'
instance Boolish [a] where
isTrue = not . null
isFalse = null
-- * Maybe and Either types
instance (Boolish a) => Boolish (Maybe a) where
isTrue (Just a) = isTrue a
isTrue _ = False
instance (Boolish b) => Boolish (Either a b) where
isTrue (Right b) = isTrue b
isTrue _ = False
-- | An overloaded @if@
iff :: Boolish a => a -- ^ test value
-> b -- ^ value if true-ish
-> b -- ^ value if false-ish
-> b
iff x f g = if isTrue x then f else g
-- | A sort of @maybe@
maybeif :: Boolish a
=> b -- ^ value if false-ish
-> (a -> b) -- ^ function to be applied if true-ish
-> a -- ^ test value
-> b
maybeif c f b = iff b (f b) c
//blue/0/~/ ghci Boolish.hs
GHCi, version 7.0.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
[1 of 1] Compiling Data.Boolish ( Boolish.hs, interpreted )
Ok, modules loaded: Data.Boolish.
ghci> let safehead xs = maybeif 0 head xs
ghci> safehead [1..9]
1
ghci> safehead []
0
ghci> let limit n xs = iff n (take n xs) xs
ghci> limit 0 [1..9]
[1,2,3,4,5,6,7,8,9]
ghci> limit 3 [1..9]
[1,2,3]
ghci>
@md2perpe

Copy link
Copy Markdown

I think that you could merge

    instance Boolish Int where
        isTrue 0 = False
        isTrue _ = True

    instance Boolish Integer where
        isTrue 0 = False
        isTrue _ = True

    instance Boolish Float where
        isTrue 0 = False
        isTrue _ = True

    instance Boolish Double where
        isTrue 0 = False
        isTrue _ = True

into

instance (Num a) => Boolish a where
    isTrue 0 = False
    isTrue _ = True

@pbrisbin

Copy link
Copy Markdown
Author

For some reason, I remember trying (almost?) exactly that and not being able to compile it. I'm sure I was just messing something up at the time...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment