Functional Python Programming

(Wang) #1
Chapter 14

Let's look at a concrete example in Python, for example, we have a function like the
following one:


from pymonad import curry


@curry


def systolic_bp(bmi, age, gender_male, treatment):


return 68.15+0.58bmi+0.65age+0.94gender_male+6.44treatment


This is a simple, multiple-regression-based model for systolic blood pressure.
This predicts blood pressure from body mass index (BMI), age, gender (1 means
male), and history of previous treatment (1 means previously treated). For more
information on the model and how it's derived, visit http://sphweb.bumc.bu.edu/
otlt/MPH-Modules/BS/BS704_Multivariable/BS704_Multivariable7.html.


We can use the systolic_bp() function with all four arguments, as follows:





systolic_bp(25, 50, 1, 0)





116.09





systolic_bp(25, 50, 0, 1)





121.59


A male person with a BMI of 25, age 50, and no previous treatment will likely have a
blood pressure of 116. The second example shows a similar woman with a history of
treatment who will likely have a blood pressure of 121.


Because we've used the @curry decorator, we can create intermediate results that are
similar to partially applied functions. Take a look at the following command snippet:





treated= systolic_bp(25, 50, 0)








treated(0)





115.15





treated(1)





121.59


In the preceding case, we evaluated the systolic_bp(25, 50, 0) method to create
a curried function and assigned this to the variable treatment. The BMI, age, and
gender values don't typically change for a given patient. We can now apply the new
function, treatment, to the remaining argument to get different blood pressure
expectations based on patient history.

Free download pdf