Added currying snippet.

This commit is contained in:
Donne Martin 2015-01-27 11:14:57 -05:00
parent 54b1c29bcc
commit 900b493e54

View File

@ -361,6 +361,75 @@
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Currying"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Currying means to derive new functions from existing ones by partial argument appilcation. Currying is used in pandas to create specialized functions for transforming time series data.\n",
"\n",
"The argument y in add_numbers is curried:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def add_numbers(x, y):\n",
" return x + y\n",
"\n",
"add_seven = lambda y: add_numbers(7, y)\n",
"add_seven(3)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 18,
"text": [
"10"
]
}
],
"prompt_number": 18
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The built-in functools can simplify currying with partial:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from functools import partial\n",
"add_five = partial(add_numbers, 5)\n",
"add_five(2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 19,
"text": [
"7"
]
}
],
"prompt_number": 19
}
],
"metadata": {}