7. Examples to try

You don’t know where to start? Here are some input expressions you can try to reduce:

Higher Order Functions

higherOrderFunctionDemo = twice double 1

twice :: (a -> a) -> a -> a
twice function number = function (function number)

double :: Num a => a -> a
double x = 2 * x

Non Strictness

nonStrictnessExample = ignoreParameter (1.0 / 0.0)

ignoreParameter :: a -> Int
ignoreParameter _ = 42

Types from the prelude

patternMatching = magicUnwrappMaybe (Just 5)

magicUnwrappMaybe :: Maybe Int -> Int
magicUnwrappMaybe (Just x) = x
magicUnwrappMaybe Nothing = 42

Functions from the prelude

recursionInput = maximum [1, 2, 3]
mapInput = head (map (+ 1) [1, 2, 3, 4, 5])
filteredList = filter even [-3, -2, -1, 1, 2, 3]

Custom types

equalityOnCustomTypeInput = change (Top 5) == Down 5

data Direction a = Top a | Down a deriving (Ord)

instance (Eq a) => Eq (Direction a) where
  (==) (Top x) (Top y) = x == y
  (==) (Top x) (Down y) = False
  (==) (Down x) (Top y) = False
  (==) (Down x) (Down y) = x == y
  (/=) (Top x) (Top y) = x /= y
  (/=) (Top x) (Down y) = True
  (/=) (Down x) (Top y) = True
  (/=) (Down x) (Down y) = x /= y

class Navigatable a where
  change :: a -> a
  doNotChange :: a -> a

instance Navigatable (Direction a) where
  change (Top x) = Down x
  change (Down x) = Top x
  doNotChange x = x

Infinite lists

infiniteListInput = sumOfTheFirstXElements [1 ..] 3

sumOfTheFirstXElements :: (Num a) => [a] -> Integer -> a
sumOfTheFirstXElements _ 0 = 0
sumOfTheFirstXElements [] _ = 0
sumOfTheFirstXElements (x : xs) amountOfElements = x + sumOfTheFirstXElements xs (amountOfElements - 1)
enumFromCharInput = enumFrom 'a' !! 3

List generation

listGenerationExample = length [ (i, j) | i <- [1, 2, 3], j <- [1, 4, 3]]

Back to the main page

Previous Chapter