Skip to content

Currying Functions

kimschles edited this page Jul 27, 2018 · 1 revision

What is currying? 🙃

kylecoberly [10:25 AM] it's a technique that's right at the border of insane functional mayhem one of the goals in FP is to have your functions have only one parameter (edited) because Reasons so if something depends on more than one piece of data, you can split it into functions that only take one argument each, and "curry" them let's say I write something like this:

  return `it's a ${item}!`  
})```
(edited)
You can extract out the function to improve readability and testability
```someCollection.map(getItemString)

function getItemString(item){
  return `it's a ${item}!`  
}```
but what if the function _also_ needs a second piece of data, like the owner?
```const owner = "Kim"

someCollection.map(item => {
  return `it's ${owner}'s ${item}!`  
})```
that works, but you can't extract out the function anymore
at least you can't do that and keep it testable
because then the `getItemString` function depends on indirect input
currying uses closures to solve that
```function getOwnerItemString(owner){
  function getItemString(item){
    return `it's ${owner}'s ${item}!`  
  }
}```
the trick is that when you call `getOwnerItemString("Kim")`, you don't get back a value- you get the function definition of `getItemString`, except _now_ it can see that `owner` value
`someCollection.map(getOwnerItemString("Kim"))`
Under the hood, that will end up getting called twice in a row, like this: `getOwnerItemString("Kim")("Backpack")`
It's called currying because it's a tribute to the mathematician Haskell Curry
and that's how currying works! :tada:
Clone this wiki locally