Stream: beginners

Topic: Type mismatch in if-then-else tutorial example


view this post on Zulip David Dunn (Dec 01 2022 at 08:17):

The example code in the if-then-else tutorial example produces a type mismatch when comparing the sum to 0. Looks like there's a constraint/typeclass/interface of some kind missing on 0. Using addAndStringify in the definition of total produces the same error for iguanas.

Code:

app "hello"
    packages { pf: "https://github.com/roc-lang/basic-cli/releases/download/0.1.1/zAoiC9xtQPHywYk350_b7ust04BmWLW00sjb9ZPtSQk.tar.br" }
    imports [pf.Stdout]
    provides [main] to pf

birds = 3

iguanas = 2

total = Num.toStr (birds + iguanas)

main =
    Stdout.line "There are \(total) animals."

addAndStringify = \num1, num2 ->
    sum = num1 + num2

    if sum == 0 then
        ""
    else
        Num.toStr sum

Output of roc dev:

── TYPE MISMATCH ──────────────────────────────────────────────────── main.roc ─

This 2nd argument to isEq has an unexpected type:

18│      if sum == 0 then
                   ^

The argument is a number of type:

    Num *

But isEq needs its 2nd argument to be:

    Num a | a has Eq

────────────────────────────────────────────────────────────────────────────────

1 error and 1 warning found in 12 ms.

You can run the program anyway with roc run

view this post on Zulip Luke Boswell (Dec 01 2022 at 08:39):

This was raised recently in zulip thread. It relates to issue 4594. If you add a type singature on the function I think that is a workaround.


Last updated: Jul 05 2025 at 12:14 UTC