Notes/Functional Programming/Basic Haskell.md
2024-12-07 21:07:38 +01:00

2.3 KiB

type
mixed

Function definitions

  • We don't have a return, we have an expression
  • Calling a function is done like this:
name arg1 arg2 ... argn

Or in this case:

add 1 2 -- This will return 3

Types

name :: <type>

Integer

x :: Integer
x = 1

Boolean

y :: Bool
y = True

Float

z :: Float
z = 1.6
  • Data Types

    • Int: platform-dependent precision integers
    • Char: character literals, functions from Data.Char module (e.g., isSpace, isDigit, isAlpha, isLower, isUpper, toLower, toUpper, digitToInt)
    • Tuple types: (e1, ..., en), functions fst and snd for pairs
  • Type classes

    • Num: numeric types (e.g., Int, Integer, Float, Double)
    • Eq: equality types, with operators == and /=
    • Ord: ordered types, with operators < and <=

More types here

Infix functions

  • Functions written between their arguments, rather than before them.
  • 5 + 3 is an infix function
  • By default, functions with symbols (like +, -, *) are infix.
  • You can also make any function infix by surrounding it with backticks (`).

Continuing with the add example, we could call it like this:

add 5 3 -- 8

but we could also do this

5 `add` 3

This achieves more natural placement of the function (in some cases).

Types in functions

We define them as a chain of types for the arguments (including the return type) with -> In the add example:

add :: Integer -> Integer -> Integer
add x y = x + y

Let

  • Save the result of an expression and then return it
  • Defines variables before the main expression
let <name> = <expression> in <result>

i.e.

let x = 5
    y = 10
in x + y -- This will "return" x+y = 15

Where

  • Inverse of let - defines variables after the main expression
  • Makes more intuitive mathematical sense
<result> where <name> = <expression>

i.e.

x + y where
  x = 5
  y = 10

If branches

If then else (ternary)

equalize x y =
  if xLarger then x - 1 else y - 1
  where
    xLarger = x > y