Expressions, Values and Basic Types
3.1 Everything Is an Expression
x :: Int
x = 42 -- a binding: x IS 42, forever
y = if x > 10 then "big" else "small" -- if is an expression (else is required)
z = let a = 3
b = 4
in sqrt (a * a + b * b) -- 5.03.2 Basic Types
Fixed-precision integer (64-bit on most platforms) 42, -7, maxBound:: Int Double / Float 3.14, 1.0e-3 Exact fractions (Data.Ratio) True / False 'a', '\n', 'λ' List of characters [Char] Unit (the empty tuple) (1, "a", True) Homogeneous, linked Word, Int8..Int64, Word8..Word64
Sized integers (Data.Int, Data.Word)
3.3 Arithmetic and Operators
Haskell has no implicit numeric conversions. Use fromIntegral, realToFrac, toInteger, round, etc.
Negative literals often need parentheses: abs (-3), not abs -3.
7 + 3 -- 10
7 - 3 -- 4
7 * 3 -- 21
7 / 2 -- 3.5 (fractional division)
7 `div` 2 -- 3 (integer division, rounds toward negative infinity)
7 `mod` 2 -- 1
(-7) `div` 2 -- -4
(-7) `quot` 2 -- -3 (rounds toward zero)
(-7) `rem` 2 -- -1
2 ^ 10 -- 1024 (integral power)
2 ** 0.5 -- 1.4142135623730951 (floating power)
2 ^^ (-1) -- 0.5 (fractional base, integral exponent)
negate 5 -- -5
abs (-3) -- 3
fromIntegral (3 :: Int) / 2 :: Double -- 1.5: convert Int to a numeric type
round 2.5, truncate 2.7, ceiling 2.1, floor 2.9 -- 2, 2, 3, 2 (round uses banker's rounding)
sqrt 16, exp 1, log 10, sin pi, pi
max 3 7, min 3 7, gcd 12 18, lcm 4 6
even 4, odd 33.4 Booleans and Comparison
True && False -- False
True || False -- True
not True -- False
5 == 5, 5 /= 4 -- True, True (/= is "not equal")
3 < 5, 'a' < 'b' -- True, True
compare 3 5 -- LT (Ordering: LT | EQ | GT)