Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created October 5, 2020 16:59
Show Gist options
  • Save kyleshevlin/d21e235ed082730bafa22a99b5a68969 to your computer and use it in GitHub Desktop.
Save kyleshevlin/d21e235ed082730bafa22a99b5a68969 to your computer and use it in GitHub Desktop.
Scheme prefix operators as functions with reduce()
// I'm reading SICP at the moment, and they use a LISP called Scheme.
// In a LISP based language, the function or operator is in the "prefix" position
// To add numbers, you first write the operator `+` (hence prefix, it comes first)
// and then the arguments.
//
// In JavaScript, many of our operators come in the "infix" position, that is in the
// middle of two arguments. This limits how many arguments we can give that operation.
//
// What's nice about the prefix position is that you can then give the expression
// as many arguments as you would like and it will apply the operation to all of those
// arguments.
//
// Here is how to write some common functions that can take any number of arguments
// in JavaScript using the rest operator and Array.prototype.reduce()
//
const add = (...nums) => nums.reduce((acc, cur) => acc + cur)
const subtract = (...nums) => nums.reduce((acc, cur) => acc - cur)
const multiply = (...nums) => nums.reduce((acc, cur) => acc * cur)
const divide = (...nums) => nums.reduce((acc, cur) => acc / cur)
console.log(add(1, 2, 3, 4, 5)) // 15
console.log(subtract(1, 2, 3, 4, 5)) // -13
console.log(multiply(1, 2, 3, 4, 5)) // 120
console.log(divide(1, 2, 3, 4, 5)) // 0.008333333333333333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment