Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of these Haskell higher-order functions?

Tags:

python

haskell

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.

like image 339
magnetar Avatar asked Feb 10 '13 04:02

magnetar


People also ask

What is higher-order functions in Python?

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.

What is a higher-order function in Haskell?

Elementary HaskellA function that takes another function (or several functions) as an argument is called a higher-order function.

Why are higher-order functions useful Haskell?

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.


2 Answers

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]
like image 76
Daniel Wagner Avatar answered Oct 24 '22 16:10

Daniel Wagner


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

like image 2
Wei Yen Avatar answered Oct 24 '22 16:10

Wei Yen