Skip to content

Instantly share code, notes, and snippets.

@threedaymonk
Last active December 16, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threedaymonk/5398637 to your computer and use it in GitHub Desktop.
Save threedaymonk/5398637 to your computer and use it in GitHub Desktop.
Hoodlums exercise suggested by Andres Löh.

From http://www.meetup.com/hoodlums/events/91349692/

Define a function cat that takes an arbitrary number of strings and returns the concatenation of all strings. You'll need the FlexibleInstances extension (but should not need any others). When calling in GHCi, you will have to annotate the result type of the function. Examples:

> cat :: String 
"" 
> cat "foo" "bar" :: String 
"foobar" 
> cat "Haskell" "Hoodlums" "Meetup" :: String 
"HaskellHoodlumnsMeetup"

If you like a follow-up exercise, then modify the function into a function count that takes an arbitrary number of String or Integer arguments and computes an Integer that is the sum of all the given integers plus the sum of the lengths of all strings. Examples:

> count :: Integer 
0
> count "foo" (7 :: Integer) "bar" :: Integer 
13

You can also try to get rid of the Integer type annotation on the argument.

{-# language FlexibleInstances #-}
module Cat where
class Concatenation t where
catNext :: String -> t
instance (Concatenation c) => Concatenation (String -> c) where
catNext args s = catNext $ args ++ s
instance Concatenation String where
catNext s = s
cat :: (Concatenation t) => t
cat = catNext ""
{-# language FlexibleInstances #-}
module Count where
class HasCountValue t where
countValue :: t -> Integer
instance HasCountValue Integer where
countValue = toInteger
instance HasCountValue String where
countValue = toInteger . length
class Accumulation t where
countNext :: Integer -> t
instance (HasCountValue a, Accumulation c) => Accumulation (a -> c) where
countNext acc v = countNext $ acc + countValue v
instance Accumulation Integer where
countNext = countValue
count :: (Accumulation t) => t
count = countNext 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment