Skip to content

Instantly share code, notes, and snippets.

@brainrake
Created July 9, 2016 02:36
Show Gist options
  • Save brainrake/1bbd575548c60bbf9d678ed26447c5fd to your computer and use it in GitHub Desktop.
Save brainrake/1bbd575548c60bbf9d678ed26447c5fd to your computer and use it in GitHub Desktop.
import Html exposing (Html, div, text)
-- give a name to an extensible record with fields common to all ducks
type alias Duck a = { a | name : String
, color : String }
-- operation common to all ducks
display : Duck a -> String
display duck = duck.name ++ " looks " ++ duck.color ++ "."
-- ways to fly
woosh : String -> String
woosh name = name ++ " flies, woosh!"
wee : String -> String
wee name = name ++ " flies, wee!"
-- stuff to say
quack : String -> String
quack name = name ++ " quacks!"
squeak : String -> String
squeak name = name ++ " squeaks!"
-- ducks
mallard : Duck { say : String, fly : String }
mallard = let name = "Mally"
in { name = name
, color = "blue"
, say = quack name -- feed data to functions
, fly = woosh name }
redhead : Duck { say : String, fly : String }
redhead = let name = "Red"
in { name = name
, color = "red"
, say = quack name
, fly = wee name }
rubber : Duck { say : String }
rubber = let name = "Rube"
in { name = name
, color = "yellow"
, say = squeak name }
main : Html ()
main = div [] <|
[ div [] [text mallard.say] -- > Mally quacks!
, div [] [text redhead.fly] -- > Red flies, wee!
, div [] [text (display rubber)] -- > Rube looks yellow.
-- , div [] [text rubber.fly]
-- -- Will not compile because rubber can't fly
-- -- in OO there is no error but nothing happens
]
-- you can extend in any direction and not have to touch anything else
-- add a way to fly or say
-- add a generic duck operation, like isRed
-- add a duck that can land
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment