1
0
Fork 0
pr3-sose2026-fork/haskell/01-expressions/README.md

3.6 KiB

Haskell - Expressions

The following illustrates some haskell basics. It can be reproduced using ghci.

Types, Literals, and Constants along with Arithmetic and Boolean Operations

Expression Type (:t) Value Comment
2 Num a => a 2
2.03 Fractional a => a 2.3
'c' Char 'c'
"hallo" String "hallo"
True Bool True
x=5 Num a => a 5 Constant named x
2 + 3 Num a => a 5 Similar -,*,^
2 / 3 Fractional a => a 0.6666666666666666
1 > 2 Bool False Similar <, <=, >=, ==, /=
True && False Bool False Similar ||,not
((2+3)*5 > 1) || not (1 > 2) Bool True Right part is not evaluated due to lazy evaluation

Unary Functions

Expression Type (:t) Value Comment
sqrt(4) Floating a => a 2.0
sqrt 4 Floating a => a 2.0 Similar abs,negate,signum,recip
sqrt Floating a => a -> a
sqrt 3^2 + 4^2 Floating a => a 19.0
sqrt (3^2 + 4^2) Floating a => a 5.0
negate(sqrt (3^2 + 4^2)) Floating a => a -5.0
negate $ sqrt (3^2 + 4^2) Floating a => a -5.0 Function application operator $
(negate . sqrt) (3^2 + 4^2) Floating a => a -5.0 Function composition operator . Reads negate after negate . sqrt
(negate . length) "hallo" Int -5
negatedRoot = negate . sqrt Floating c => c -> c Constant named negatedRoot

Binary Functions

Expression Type (:t) Value Comment
div 8 4 Integral a => a 2 Similar mod,gcd,lcm,not
8 `div` 4 Integral a => a 2 Infix notation using backticks
8 + 4 Num a => a 12 -,*,^,<, <=, >=, ==, /=
(+) 8 4 Num a => a 12 Prefix notation using parenthesis
div Integral a => a -> a -> a Currying represents multi-argument functions as a chain of single-argument functions
div 8 Integral a => a -> a binds the first argument; Similar (8/),(8*),(8+),(8-)
div8bySomething = div 8 Integral a => a -> a
div8bySomething 4 Integral a => a 2
uncurry div Integral c => (c, c) -> c accepts a single tuple argument
uncurry div (8,4) Integral c => c 2
uncurry (a -> b -> c) -> (a, b) -> c
(`div` 4) Integral a => a -> a Sectioning binds the second argument of infix functions; Similar (/8),(*8),(+8),(-8)
divSomethingBy4 = (`div` 4) Integral a => a -> a
divSomethingBy4 8 Integral a => a 2

Tuples

Expression Type (:t) Value Comment
(1, 2) (Num a, Num b) => (a, b) (1, 2)
(1, "hello", True) (Num a => (a, String, Bool) (1, "hello", True)
fst (1, 2) Num a => a 1
snd (1, 2) Num b => b 2
(,) 1 2 Num a => a -> a -> (a, a) (1, 2)

Strings

Expression Type (:t) Value Comment
"hello" ++ " world" String "hello world" String concatenation
length "hello" Int 5 Length of the string
null "" Bool True Checks if the string is empty

Control Structures

Expression Type (:t) Value Comment
if 10/2==5 then "five" else "something else" String "five"
case 1 of { 1 -> "small"; 2 -> "medium"; _ -> "large"} String "small" patterns are overlapping
(let x = 5*2 in (x * 2,x /2)) (Fractional b, Num a) => (a, b) (20,5.0)

Lists