Jan-29-2024, 06:51 AM
Hello.
Let's make a co-recursive class, or unfoldr somehow popular among functional programming folks, relying on its definition of the Haskell programming language, designed with a Python's fancy iterator.
The code of its solution is something like below, using the unfoldr iterator.
The logic is almost as same as the above code shown, though we use the "statistics.mean" module/function because writing "average" is dull.
Could anybody explain what happens?
Thanks, regards.
Let's make a co-recursive class, or unfoldr somehow popular among functional programming folks, relying on its definition of the Haskell programming language, designed with a Python's fancy iterator.
class unfoldr: def __init__(self, f, seed): self.f = f self.seed = seed def __iter__(self): return self def __next__(self): match self.f(self.seed): case a, b: self.seed = b return a case None: raise StopIterationNow, let's solve the problem below.
Quote:You input numbers. If you input 0, it means stopping input. Write a program showing the sum you have inputted.
The code of its solution is something like below, using the unfoldr iterator.
def bar(): def foo(x): i = int(input()) return None if i == 0 else (i, x + 1) print(sum(unfoldr(foo, 0)))You may run the code without any problems.
>>> bar() 1 2 3 4 5 6 7 8 9 10 0 55Next, try solving a similar problem as below.
Quote:You input numbers. If you input 0, it means stopping input. Write a program showing the average you have inputted.
The logic is almost as same as the above code shown, though we use the "statistics.mean" module/function because writing "average" is dull.
def buzz(): from statistics import mean def foo(x): i = int(input()) return None if i == 0 else (i, x + 1) print(mean(unfoldr(foo, 0)))Here comes the problem. Even though the logic of the function, buzz, is as same as the logic of the function, bar, buzz needs 0 twice to stop inputting and return its result.
>>> buzz() 1 2 3 4 5 6 7 8 9 10 0 # the first 0 0 # the second 0 -> that makes buzz finished and return the result 5.5I do not understand why this weird fact occurs.
Could anybody explain what happens?
Thanks, regards.