Built-in types
PureScript | JavaScript | Example Values |
---|---|---|
Number | number | 1.0 |
String | string | "test" |
Boolean | boolean | true |
Int | int | 2 |
Char | char | 'b' |
Array | array | [1,2,3] [true, false] |
Record | object | {"name": "John", "age": 30} |
More types can be found from language reference(https://github.com/purescript/documentation/blob/master/language/Types.md)
Value has a type
> :type 12
Int
> :type 'a'
Char
> :type [1,2,3]
Array Int
type name starts with upper case, like Int, Char, etc.
Type has a kind
> :kind Int
> Type
> :kind Char
> Type
Type is a special kind which represents the kind of all types which have values, like Number and String.
Static Type System
What is a type
A type is a kind of label that every expression has. It tells us in which category of things that expression fits. The expression True is a boolean, "hello" is a string, etc.
- everything in PureScript has a type
- the type of every expression (vs. statement) is known at compile time. And it only exists at compile time
Type inference
- Infer type by itself, don't have to tell explicitly
- function also has type
- it's good practice to give them explicit declaration
If you want to give your function a type declaration but are unsure as to what it should be, you can always just write the function without it and then check it with :t
(or :type
). Functions are expressions too, so :t works on them without a problem.
> hello x = "hello " <> x
> :type hello
String -> String
> double x = x * 2
> :type double
Int -> Int
> add x y = x + y
> :type add
forall (a9 :: Type). Semiring a9 => a9 -> a9 -> a9
Type variable
> :type (+)
forall (@a :: Type). Semiring a => a -> a -> a
> :type (-)
forall (@a :: Type). Ring a => a -> a -> a
> :type (==)
forall (@a :: Type). Eq a => a -> a -> Boolean
what is a?
- is not a type, because types are written in capital case.
- it is a type variable
Functions that have type variables are called polymorphic functions.
pattern matching on data constructor
data Shape = Circle Number | Rectangle Number Number
area :: Shape -> Number
area (Circle r) = 3.14 * r * r
area (Rectangle w h) = w * h
-> just like function
Rows
https://github.com/purescript/documentation/blob/master/language/Types.md#rows Rows are not of kind Type: they have kind Row k for some kind k, and so rows cannot exist as a value