Skip to content

Instantly share code, notes, and snippets.

@saschatimme
Created May 29, 2016 10:51
Show Gist options
  • Save saschatimme/ea336cc7f487de04ca43c38e3a1a4fdc to your computer and use it in GitHub Desktop.
Save saschatimme/ea336cc7f487de04ca43c38e3a1a4fdc to your computer and use it in GitHub Desktop.
Functional Programming for JavaScript People examples in Elm
{- js
const add1 = (a) => a + 1
const times2 = (a) => a * 2
const compose = (a, b) => (c) => a(b(c))
const add1OfTimes2 = compose(add1, times2)
add1OfTimes2(5) // => 11
-}
add1 = (+) 1
times2 = (*) 2
add1OfTimes2 = add1 << times2
-- shorter ( Haskell / Elm is left-assocative [ a b c == ((a b) c) ])
add1OfTimes2 = (+) 1 << (*) 2
{- js
const pipe = (fns) => (x) => fns.reduce((v, f) => f(v), x)
const times2add1 = pipe([times2, add1])
times2add1(5) // => 11
-}
-- pipe example
times2add1 x =
x
|> (*) 2
|> (+) 1
{- js
const formalGreeting = (name) => `Hello ${name}`
const casualGreeting = (name) => `Sup ${name}`
const male = (name) => `Mr. ${name}`
const female = (name) => `Mrs. ${name}`
const doctor = (name) => `Dr. ${name}`
const phd = (name) => `${name} PhD`
const md = (name) => `${name} M.D.`
formalGreeting(male(phd("Chet"))) // => "Hello Mr. Chet PhD"
const identity = (x) => x
const greet = (name, options) => {
return pipe([
// greeting
options.formal ? formalGreeting :
casualGreeting,
// prefix
options.doctor ? doctor :
options.male ? male :
options.female ? female :
identity,
// suffix
options.phd ? phd :
options.md ?md :
identity
])(name)
}
-}
type Greeting = Formal | Casual
type Title = Doctor | Male | Female
type Degree = Md | Phd | NoDegree
prefix a b = a ++ " " ++ b
suffix a b = b ++ " " ++ a
addGreeting greeting name =
case greeting of
Formal ->
prefix "Hello" name
Casual ->
prefix "Sup" name
addTitle title name =
case title of
Doctor ->
prefix "Dr." name
Male ->
prefix "Mr." name
Female ->
prefix "Mrs." name
addDegree degree name =
case degree of
Md ->
suffix "M.D." name
Phd ->
suffix "PhD" name
NoDegree ->
name
greet greeting title degree name =
name
|> addTitle title
|> addGreeting greeting
|> addDegree degree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment