Created
February 26, 2015 00:12
-
-
Save stuartweir/ce6e037507d1162209e1 to your computer and use it in GitHub Desktop.
Learning about functional programming, inheritance, etc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write a function that takes an argument and | |
// returns that argument. | |
function identity(id) { | |
return id; | |
} | |
// Write two binary functions, 'add' and 'mul', | |
// that take two numbers and return their sum and product. | |
function add(x, y) { | |
return x + y; | |
} | |
function mul(x, y) { | |
return x * y; | |
} | |
// Write a function that takes an argument and returns | |
// a function that returns that argument. | |
function identityf(x) { | |
return function() { | |
return x; | |
}; | |
} | |
// Write a function that adds from two invocations | |
function addf(x) { | |
return function(y) { | |
return x + y; | |
}; | |
} | |
// Write a function that takes a binary function, and | |
// makes it callable with two invocations. | |
function applyf(binFunc) { | |
return function (x) { | |
return function (y) { | |
return binary(x, y); | |
}; | |
}; | |
} | |
// Write a function that takes a function and an argument, | |
// and returns a function that can supply a second argument. | |
function curry(binary, x) { | |
return function (y) { | |
return binary(x, y); | |
}; | |
} | |
// Without without writing any new functions, | |
// show three ways to create the 'inc' function. | |
// inc(5) // 6 | |
// inc(inc(5)) // 7 | |
inc = addf(1); | |
inc = applyf(add)(1); | |
inc = curry(add, 1); | |
// ****** I Don't know how using these three can make inc(5) into 6. | |
// In addf, for example, how is the function getting the y value? is | |
// the y value what the value of inc already is? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment