Stream: beginners

Topic: force Num type


view this post on Zulip Ghislain (Dec 03 2022 at 16:13):

For AoC, I need to call List.sum on a list of U8. But it crash with an "integer addition overflowed". How can I avoid it and force the List.sum to return a U32?

» a : List U8
… a = [127, 127, 127, 127]

[127, 127, 127, 127] : List U8
                             # a
» List.sum a
This Roc code crashed with: "integer addition overflowed!"

<function> : U8           # val1

view this post on Zulip Anton (Dec 03 2022 at 16:21):

You can do a List.map with Num.toU32 on the list before doing the List.sum

view this post on Zulip Anton (Dec 03 2022 at 16:22):

We should improve the "integer addition overflowed!" error message.

view this post on Zulip Ghislain (Dec 03 2022 at 16:22):

Yes, that's what I found, but I was wondering if there was a way to do it otherwise (force the output of List.sum to be something else).

view this post on Zulip Ghislain (Dec 03 2022 at 16:24):

The definition is clear though: List (Num a) -> Num a

view this post on Zulip Anton (Dec 03 2022 at 16:27):

It is possible to make a builtin for that but it seems like a very niche use case. The List.map solution is pretty clear. I don't think trying to make this whole operation shorter would be nicer.

view this post on Zulip Anton (Dec 03 2022 at 16:31):

The a in List (Num a) -> Num a is used in input and output of the function so the input number type has to be the same as the output number type. But perhaps that's what you meant with The definition is clear though.

view this post on Zulip Brendan Hansknecht (Dec 03 2022 at 16:40):

Can always manually write a List.walk with the conversion in it. Shouldn't be too complex, but definitely less convenient.

view this post on Zulip Brendan Hansknecht (Dec 03 2022 at 16:42):

Something like:
List.walk listU8 0, \accum, elem -> accum + Num.toU32 elem


Last updated: Jul 05 2025 at 12:14 UTC