Basics

Tons of useful functions that get imported by default.

Numbers

type Int

An Int is a whole number. Valid syntax for integers includes:

0

42

9000

0xFF -- 255 in hexadecimal

0x0A --  10 in hexadecimal

Note: Int math is well-defined in the range -2^31 to 2^31 - 1. Outside of that range, the behavior is determined by the compilation target. When generating JavaScript, the safe range expands to -(2^53 - 1) to 2^53 - 1 for some operations, but if we generate WebAssembly some day, we would do the traditional integer overflow. This quirk is necessary to get good performance on quirky compilation targets.

Historical Note: The name Int comes from the term integer. It appears that the int abbreviation was introduced in ALGOL 68, shortening it from integer in ALGOL 60. Today, almost all programming languages use this abbreviation.

(+) : number -> number -> number

Add two numbers. The number type variable means this operation can be specialized to Int -> Int -> Int or to Float -> Float -> Float. So you can do things like this:

3002 + 4004 == 7006 -- all ints

3.14 + 3.14 == 6.28 -- all floats

You cannot add an Int and a Float directly though. Use functions like toFloat or round to convert both values to the same type. So if you needed to add a array length to a Float for some reason, you could say one of these:

3.14 + toFloat (Array.length [ 1, 2, 3 ]) == 6.14

round 3.14 + Array.length [ 1, 2, 3 ] == 6

Note: Languages like Java and JavaScript automatically convert Int values to Float values when you mix and match. This can make it difficult to be sure exactly what type of number you are dealing with. When you try to infer these conversions (as Scala does) it can be even more confusing. Gren has opted for a design that makes all conversions explicit.

(-) : number -> number -> number

Subtract numbers like 4 - 3 == 1.

See (+) for docs on the number type variable.

(*) : number -> number -> number

Multiply numbers like 2 * 3 == 6.

See (+) for docs on the number type variable.

(/) : Float -> Float -> Float

Floating-point division:

10 / 4 == 2.5

11 / 4 == 2.75

12 / 4 == 3

13 / 4 == 3.25

14
    / 4
    == 3.5
    - 1
    / 4
    == -0.25
    - 5
    / 4
    == -1.25
(//) : Int -> Int -> Int

Integer division:

10 // 4 == 2

11 // 4 == 2

12 // 4 == 3

13 // 4 == 3

14
    // 4
    == 3
    - 1
    // 4
    == 0
    - 5
    // 4
    == -1

Notice that the remainder is discarded, so 3 // 4 is giving output similar to truncate (3 / 4).

It may sometimes be useful to pair this with the remainderBy function.

(^) : number -> number -> number

Exponentiation

3 ^ 2 == 9

3 ^ 3 == 27
negate : number -> number

Negate a number.

negate 42 == -42

negate -42 == 42

negate 0 == 0

Float

type Float

A Float is a floating-point number. Valid syntax for floats includes:

0
42
3.14
0.1234
6.022e23   -- == (6.022 * 10^23)
6.022e+23  -- == (6.022 * 10^23)
1.602e−19  -- == (1.602 * 10^-19)
1e3        -- == (1 * 10^3) == 1000

Historical Note: The particular details of floats (e.g. NaN) are specified by IEEE 754 which is literally hard-coded into almost all CPUs in the world. That means if you think NaN is weird, you must successfully overtake Intel and AMD with a chip that is not backwards compatible with any widely-used assembly language.

toFloat : Int -> Float

Convert an integer into a float. Useful when mixing Int and Float values like this:

halfOf : Int -> Float
halfOf number =
    toFloat number / 2
isNaN : Float -> Bool

Determine whether a float is an undefined or unrepresentable number. NaN stands for not a number and it is a standardized part of floating point numbers.

isNaN (0 / 0) == True

isNaN (sqrt -1) == True

isNaN (1 / 0) == False -- infinity is a number

isNaN 1 == False
isInfinite : Float -> Bool

Determine whether a float is positive or negative infinity.

isInfinite (0 / 0) == False

isInfinite (sqrt -1) == False

isInfinite (1 / 0) == True

isInfinite 1 == False

Notice that NaN is not infinite! For float n to be finite implies that not (isInfinite n || isNaN n) evaluates to True.

Equality

(==) : a -> a -> Bool

Check if values are “the same”.

Note: Gren uses structural equality on tuples, records, and user-defined union types. This means the values (3, 4) and (3, 4) are definitely equal. This is not true in languages like JavaScript that use reference equality on objects.

Note: Do not use (==) with functions, JSON values from gren/json, or regular expressions from gren/regex. It does not work. It will crash if possible. With JSON values, decode to Gren values before doing any equality checks!

Why is it like this? Equality in the Gren sense can be difficult or impossible to compute. Proving that functions are the same is undecidable, and JSON values can come in through ports and have functions, cycles, and new JS data types that interact weirdly with our equality implementation. In a future release, the compiler will detect when (==) is used with problematic types and provide a helpful error message at compile time. This will require some pretty serious infrastructure work, so the stopgap is to crash as quickly as possible.

(/=) : a -> a -> Bool

Check if values are not “the same”.

So (a /= b) is the same as (not (a == b)).

Comparison

These functions only work on comparable types. This includes numbers, characters, strings and arrays of comparable things.

type Order
= LT
| EQ
| GT

Represents the relative ordering of two things. The relations are less than, equal to, and greater than.

(<) : comparable -> comparable -> Bool
(>) : comparable -> comparable -> Bool
(<=) : comparable -> comparable -> Bool
(>=) : comparable -> comparable -> Bool
max : comparable -> comparable -> comparable

Find the larger of two comparables.

max 42 12345678 == 12345678

max "abc" "xyz" == "xyz"
min : comparable -> comparable -> comparable

Find the smaller of two comparables.

min 42 12345678 == 42

min "abc" "xyz" == "abc"
clamp : number -> number -> number -> number

Clamps a number within a given range. With the expression clamp 100 200 x the results are as follows:

100     if x < 100
 x      if 100 <= x < 200
200     if 200 <= x
compare : comparable -> comparable -> Order

Compare any two comparable values. Comparable values include String, Char, Int, Float, or an array or tuple containing comparable values. These are also the only values that work as Dict keys or Set members.

compare 3 4 == LT

compare 4 4 == EQ

compare 5 4 == GT

Booleans

type Bool
= True
| False

A “Boolean” value. It can either be True or False.

Note: Programmers coming from JavaScript, Java, etc. tend to reach for boolean values way too often in Gren. Using a union type is often clearer and more reliable. You can learn more about this from Jeremy here or from Richard here.

not : Bool -> Bool

Negate a boolean value.

not True == False

not False == True
(&&) : Bool -> Bool -> Bool

The logical AND operator. True if both inputs are True.

True && True == True

True && False == False

False && True == False

False && False == False

Note: When used in the infix position, like (left && right), the operator short-circuits. This means if left is False we do not bother evaluating right and just return False overall.

(||) : Bool -> Bool -> Bool

The logical OR operator. True if one or both inputs are True.

True || True == True

True || False == True

False || True == True

False || False == False

Note: When used in the infix position, like (left || right), the operator short-circuits. This means if left is True we do not bother evaluating right and just return True overall.

xor : Bool -> Bool -> Bool

The exclusive-or operator. True if exactly one input is True.

xor True True == False

xor True False == True

xor False True == True

xor False False == False

Append Strings and Arrays

(++) : appendable -> appendable -> appendable

Put two appendable things together. This includes strings and arrays.

"hello" ++ "world" == "helloworld"

[ 1, 1, 2 ] ++ [ 3, 5, 8 ] == [ 1, 1, 2, 3, 5, 8 ]

Function Helpers

identity : a -> a

Given a value, returns exactly the same value. This is called the identity function.

(<|) : (a -> b) -> a -> b

Saying f <| x is exactly the same as f x.

It can help you avoid parentheses, which can be nice sometimes. Maybe you want to apply a function to a case expression? That sort of thing.

(|>) : a -> (a -> b) -> b

Saying x |> f is exactly the same as f x.

It is called the “pipe” operator because it lets you write “pipelined” code. For example, say we have a sanitize function for turning user input into integers:

-- BEFORE
sanitize : String -> Maybe Int
sanitize input =
    String.toInt (String.trim input)

We can rewrite it like this:

-- AFTER
sanitize : String -> Maybe Int
sanitize input =
    input
        |> String.trim
        |> String.toInt

Totally equivalent! I recommend trying to rewrite code that uses x |> f into code like f x until there are no pipes left. That can help you build your intuition.

Note: This can be overused! I think folks find it quite neat, but when you have three or four steps, the code often gets clearer if you break out a top-level helper function. Now the transformation has a name. The arguments are named. It has a type annotation. It is much more self-documenting that way! Testing the logic gets easier too. Nice side benefit!

(<<) : (b -> c) -> (a -> b) -> a -> c

Function composition, passing results along in the suggested direction. For example, the following code checks if the result of rounding a float is odd:

not << isEven << round

You can think of this operator as equivalent to the following:

(g << f) == (\x -> g (f x))

So our example expands out to something like this:

\n -> not (isEven (round n))
(>>) : (a -> b) -> (b -> c) -> a -> c

Function composition, passing results along in the suggested direction. For example, the following code checks if the result of rounding a float is odd:

round >> isEven >> not
type Never

A value that can never happen! For context:

  • The boolean type Bool has two values: True and False
  • The unit type () has one value: ()
  • The never type Never has no values!

You may see it in the wild in Html Never which means this HTML will never produce any messages. You would need to write an event handler like onClick ??? : Attribute Never but how can we fill in the question marks?! So there cannot be any event handlers on that HTML.

You may also see this used with tasks that never fail, like Task Never ().

The Never type is useful for restricting arguments to a function. Maybe my API can only accept HTML without event handlers, so I require Html Never and users can give Html msg and everything will go fine. Generally speaking, you do not want Never in your return types though.

never : Never -> a

A function that can never be called. Seems extremely pointless, but it can come in handy. Imagine you have some HTML that should never produce any messages. And say you want to use it in some other HTML that does produce messages. You could say:

import Html exposing (..)

embedHtml : Html Never -> Html msg
embedHtml staticStuff =
    div []
        [ text "hello"
        , Html.map never staticStuff
        ]

So the never function is basically telling the type system, make sure no one ever calls me!