Skip to content

Instantly share code, notes, and snippets.

@eHammarstrom
Last active January 23, 2018 16:13
Show Gist options
  • Save eHammarstrom/c0f986c954dd4661f5829dabaef71b3c to your computer and use it in GitHub Desktop.
Save eHammarstrom/c0f986c954dd4661f5829dabaef71b3c to your computer and use it in GitHub Desktop.
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ExistentialQuantification #-}
--
-- An animal that weighs < 5kg are deemed sick. Do we have any sick animals on our farm?
--
data Cow = Cow { weightC :: Integer, color :: String } deriving (Show)
data Sheep = Sheep { weightS :: Integer, fluffinessFactor :: Double } deriving (Show)
data Dog = Dog { weightD :: Integer, barks :: Bool } deriving (Show)
class Weighable a where
weight :: a -> Integer
instance Weighable Cow where
weight = weightC
instance Weighable Sheep where
weight = weightS
instance Weighable Dog where
weight = weightD
cowses = [Cow { weightC = 11, color = "blue" }, Cow { weightC = 21, color = "yellow" }]
sheepses = [Sheep { weightS = 4, fluffinessFactor = 0.1 }, Sheep { weightS = 15, fluffinessFactor = 2.3 }]
dogses = [Dog { weightD = 12, barks = False }]
--
-- 1st solution
--
containsSick :: Weighable a => [a] -> Bool
containsSick = any ((<5) . weight)
solution1 :: Bool
solution1 = containsSick cowses || containsSick sheepses || containsSick dogses
--
-- 2nd solution, why?
--
data Weighables = forall a. Weighable a => WS a
instance Weighable Weighables where
weight (WS a) = weight a
animals :: [Weighables]
animals = map WS cowses ++ map WS sheepses ++ map WS dogses
solution2 :: Bool
solution2 = containsSick animals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment