The chapter on Partial Functions from the book Learn You a Haskell For Great Good contains the following code:
multThree :: (Num a) => a -> a -> a -> a
multThree x y z = x * y * z
ghci> let multTwoWithNine = multThree 9
ghci> multTwoWithNine 2 3
54
ghci> let multWithEighteen = multTwoWithNine 2
ghci> multWithEighteen 10
180
I am currently playing with the functools library in Python, and managed to replicate the behavior of those functions using it.
from functools import partial
def multThree(x,y,z):
return x * y * z
>>> multTwoWithNine = partial(multThree,9)
>>> multTwoWithNine(2,3)
>>> multWithEighteen = partial(multTwoWithNine,2)
>>> multWithEighteen(10)
180
One thing I would now like to do is see if I can replicate some of the more interesting higher-order functions from the same book chapter, such as:
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
However, I'm not sure how to do this, or if partial()
is even useful here.
In high order function, a function can act as an instant of an object type. In high order function, we can return a function as a result of another function. In high order function, we can pass a function as a parameter or argument inside another function.
Elementary HaskellA function that takes another function (or several functions) as an argument is called a higher-order function.
A higher-order function is technically any function that takes another function as an argument. Typically, when higher-order functions are mentioned, a specific group of them comes to mind, and nearly all of these are used to abstract away common patterns of recursion.
Python's built-in map
function behaves like Haskell's zipWith
:
>>> def add(x,y): return x + y
...
>>> map(add,[1,2,3],[10,20,30])
[11, 22, 33]
def add(a, b):
return a + b
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
>> map(add, x, y)
[6, 8, 10, 12]
Also, do check out the Python builtin itertools
module: http://docs.python.org/2/library/itertools.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With