Funkcionálne programovanie
@dataclass
class CumulativeAvg:
avg: float = 0
num: int = 0
current = CumulativeAvg()
def new_average(x: float) -> float:
current.avg = current.avg + (x - current.avg) / (current.num + 1)
current.num += 1
return current.avg
@dataclass
class CumulativeAvg:
avg: float = 0
num: int = 0
def new_average(current: CumulativeAvg, x: float) -> CumulativeAvg:
return CumulativeAvg(
current.avg + (x - current.avg) / (current.num + 1),
(current.num + 1))
def hello() -> None:
print("Hello!")
def hello() -> str:
return "Hello!"
def add(x: int, y: int) -> int:
return x + y
def add() -> int:
x = int(input("x? "))
y = int(input("y? "))
return x + y
$$ \begin{array}{l} f :: T_1 \rightarrow T_2 \rightarrow \dots \rightarrow T_n \rightarrow T \\ f \; x_1 \; x_2 \; \dots \; x_n = e \end{array} $$
add :: Int -> Int -> Int
add x y = x + y
->
?->
asociuje doprava
add :: Int -> Int -> Int
add :: Int -> (Int -> Int)
Aplikácia asociuje zľava
add 1 2 == (add 1) 2
Čiastočná aplikácia funkcie
map (add 5) [1..5]
filter (elem 'a') words
Currying: funkcia ľubovoľnej arity → unárna funkcia
def add(x, y):
return x + y
from functools import partial
add(1, 2) == partial(add, 1)(2)
add1 = partial(add, 1)
add1(2)
True
a False
Pair 1 2
, alebo (1, 2)
add 2 (square 3)
add 2 (9)
, alebo 2 + 3*3
11
add 2 (square 3)
⇒ add 2 (3 * 3)
⇒ add 2 9
⇒ 2 + 9
⇒ 11
add 2 (square 3)
⇒ 2 + (square 3)
⇒ 2 + (3 * 3)
⇒ 2 + 9
⇒ 11
infinity n = n : infinity (n + 1)
take n _ | n <= 0 = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
take 2 (infinity 1)
take 2 (1 : infinity (1 + 1))
1 : take (2 - 1) (infinity (1 + 1))
1 : take 1 (infinity (1 + 1))
1 : take 1 ((1 + 1) : infinity ((1 + 1) + 1))
1 : (1 + 1) : (take (1 - 1) (infinity ((1 + 1) + 1))
1 : 2 : (take (1 - 1) (infinity ((1 + 1) + 1))
1 : 2 : (take 0 (infinity ((1 + 1) + 1))
1 : 2 : []
def infinity(n):
while True:
yield n
n += 1
import itertools
list(itertools.islice(infinity(1), 5))
IntStream.iterate(1, i -> i+1).limit(5).toArray()
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
fib n = fibs!!n