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

The chapter on partial functions from Learn You 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 am able to replicate the behavior of these 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 like to do now is to see if I can reproduce some of the more interesting higher-order functions from the same chapter of the book, for example:

zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys

However, I am not sure how to do this, or partial()even if it is useful here.

+5
source share
4 answers

The mapPython built-in function behaves like a Haskell zipWith:

>>> def add(x,y): return x + y
... 
>>> map(add,[1,2,3],[10,20,30])
[11, 22, 33]
+5
source
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]

, itertools Python: http://docs.python.org/2/library/itertools.html

+2

Python zipWith', :

def zip_with(f, l1, l2):
    if len(l1) == 0 or len(l2) == 0:
        return []
    else:
        return [f(l1[0], l2[0])] + zip_with(f, l1[1:], l2[1:])

, Haskell. -, , Python ; len, [0] [1:]. -, Python , zip_with , . , , Python ( ?) 1000, , 1000 .

.

0

This is a good candidate for using the built-in zip function and list comprehension:

>>> zip_with = lambda fn, la, lb: [fn(a, b) for (a, b) in zip(la, lb)]

>>> add2 = lambda x,y: x+y
>>> zip_with(add2, range(10), range(1,11))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
0
source

All Articles