Haskell for Python: a problem with converting multiple functions

I am new to programming and I was asked to convert 3 haskell functions in python as an exercise. 3 functions are connected, since the output of one of them is used as the input of the next, etc.

I get what haskell functions do, but I don't know how to start converting them!

This is the haskell code:

factorial :: Int -> Int factorial n = product (down n) product :: [Int] -> Int product [] = 1 product (a:as) = a * product as down :: Int -> [Int] down 0 = [] down n = n : down (n-1) 

And it was my attempt to convert it:

 class function: def down(self): if self.n == 0: self.lista = [] else: self.lista = range(self.n, 0, -1) def product(self): for x in self.lista: if x == []: self.product = 1 if x != []: for i in self.lista: self.product = i * self.product def factorial(self): self.n = int(raw_input("n=")) self.fact = self.product(self.down(self.n)) print self.fact raw_input() c = function() c.factorial() 

Well, at first I think this is not a โ€œdirect conversionโ€ of haskell code. It will be good, but, secondly, it will not work.

This lack of background programming is killing me ... can someone help me with this problem?

Thanks a lot!

Edit:

The goal of this problem is to accurately convert haskell to python. I made my personal version, it was the next step in the exercise ^^

+4
source share
2 answers

First, turn off the class wrapper - which is not needed.

A direct Python translation would be something like this:

 # factorial :: Int -> Int def factorial(n): return product(down(n)) # product :: [Int] -> Int def product(arr): if len(arr) == 0: return 1 a, ar = arr[0], arr[1:] return a * product(ar) # down :: Int -> [Int] def down(n): if n == 0: return [] return [n] + down(n - 1) 

But the recursive style here is not very Pythonic. Next Exercise: Replace recursion with iteration, lists, or calls with reduce (if in Python2).

+7
source

If you want to write idiomatic Python, avoid recursion.

down(n) is written as range(n, 0, -1) . Use xrange if you need lazy semantics that are closer to the Haskell spirit.

product(lst) - reduce(operator.mul, lst, 1) . (It would be more idiomatic just to write a loop, but this is shorter.)

From there, it should be obvious how to convert factorial .

+4
source

Source: https://habr.com/ru/post/1443500/


All Articles