Created
April 24, 2016 11:16
-
-
Save janwirth/7db0773643f68f02256d7db7b1be8848 to your computer and use it in GitHub Desktop.
Modularisation of reduce with functional programming as described by Hughes http://ipaper.googlecode.com/git-history/8070869c59470de474515000e3af74f8958b2161/John-Hughes/The%20Computer%20Journal-1989-Hughes-98-107.pdf
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
# a function that takes a function and returns a function | |
reduce = (operation) -> | |
# the returned function accepts a list | |
(list) -> | |
# and applies the operation passed to the outer function recursively to the list | |
if list.length > 2 | |
return operation list[0], reduce(operation)(list.slice(1, list.length)) | |
# until it is empty | |
else | |
return operation list[0], list[1] | |
# basic mathematical operations that take two arguments | |
add = (a, b) -> a + b | |
multiply = (a, b) -> a * b | |
# combine these operations with reduce to create specialised reduce functions | |
sum = reduce add | |
factorial = reduce multiply | |
console.log() | |
console.log sum [3 .. 6] # 3 + 4 + 5 + 6 | |
console.log() | |
console.log factorial [2 .. 4] # 2 * 3 * 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment