Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save laser/b58be58156d43d5295ac to your computer and use it in GitHub Desktop.

Select an option

Save laser/b58be58156d43d5295ac to your computer and use it in GitHub Desktop.
Haskell Type Class Basics
module Main where
-- essentially we're defining functions that makes sense to
-- call with things that can be doubled. it can be, well,
-- a value of any type (as long as that type instantiates
-- the Dubbleable type class). Dispatch can happen by virtue
-- of what you're going to do with the return value of the
-- function or what you're passing to the function as its
-- arguments
--
class Dubbleable t where
dubble :: t -> t
-- this implementation of dubble will be used if you
-- call dubble with a list of whatever
--
instance Dubbleable [a] where
dubble list = list ++ list
-- this implementation will be used if you call dubble
-- with an Integer
--
instance Dubbleable Integer where
dubble n = n * 2
main :: IO ()
main = do
putStrLn $ show $ dubble [1, 2, 3] -- here, we dispatch based on the input to the function
putStrLn $ show $ ((dubble 25) :: Integer) -- here, we dispatch based on the expected return type of the function
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment