{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Interactions\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda Functions ###\n", "\n", "(anonymous functions)\n", "from Lisp & functional programming" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tmp = lambda x: x**2\n", "print(type(tmp))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tmp(2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# forget about creating a new function name...just do it!\n", "(lambda x,y: x**2+y)(2,4.5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## create a list of lambda functions\n", "lamfun = [lambda x: x**2, lambda x: x**3, \\\n", " lambda y: math.sqrt(y) if y >= 0 else \"Really? I mean really? %f\" % y]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for l in lamfun: print(l(-1.3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "lambda functions are meant to be short, one liners. If you need more complex functions, probably better just to name them\n", "