Functions
A function is a mapping from values of one type to values of another type.
Function Definition and Application
add :: Integer -> Integer -> Integer
add x y = x + y
add 1 2
Polymorphic Functions
length :: forall a. [a] -> Integer
-- example
nats25 :: [Integer]
nats25 = [0..25]
letters :: [Char]
letters = ['a'..'z']
n1 = length nats25 -- 26
n2 = length letters -- 26
zip :: forall a b. [a] -> [b] -> [(a,b)]
ordL = zip nats letters
-- [(0,'a'),(1,'b'),(2,'c'),(3,'d'),(4,'e'),(5,'f'),(6,'g'),(7,'h'),(8,'i'),(9,'j'),(10,'k'),(11,'l'),(12,'m'),(13,'n'),(14,'o'),(15,'p'),(16,'q'),(17,'r'),(18,'s'),(19,'t'),(20,'u'),(21,'v'),(22,'w'),(23,'x'),(24,'y'),(25,'z')]
Currying
-- uncurried
plus :: (Integer, Integer) -> Integer
plus (x, y) = x + y
-- sum is the curried version of plus
sum :: Integer -> Integer -> Integer
sum x y = x + y
Partial application
sum 1 2 :: Integer
sum 1 (2 + 3) :: Integer
add2 = sum 2 :: Integer -> Integer -- partially applied
x = add2 3 :: Integer -- x = 5
High-Order Functions
apply :: forall a b. (a -> b) -> a -> b
apply f x = f x
Recursive Function
fact n = if n == 0 then 1 else n * fact (n - 1)
length [] = 0
length [x|xs] = length xs + 1
Lambda (Anonymous Function)
multBy :: Integer -> Integer -> Integer
multBy n = \m -> m * n
mean :: Integer -> Integer -> Integer
mean = \x y -> (x + y) `div` 2 -- f = (\x -> \y -> (x + y) `div` 2)
Function Pattern Matching
(x, y) = (1, 2)
-- function declartion via pattern matching
allEmpty [] = True
allEmpty _ = False
-- pattern matching stops when it finds the first match
Guarded Equations
abs n | n > 0 = n
| otherwise = -n
当前内容版权归 hamler-lang 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 hamler-lang .