I'm extracting a the first record from a list and then trying to use use a field from it:
item = List.first items
aspectRatio = item.width / item.height
And getting this error:
── TYPE MISMATCH in Layout.roc ─────────────────────────────────────────────────
This expression is used in an unexpected way:
37│ aspectRatio = (Num.toFrac item.width) / (Num.toFrac item.height)
^^^^^^^^^^
This item value is a:
Result GalleryItem [ListWasEmpty]
But you are trying to use it as:
{ width : * }b
────────────────────────────────────────────────────────────────────────────────
1 error and 3 warnings found in 849 ms
Does anyone know what this means?
Full code: https://github.com/ashleydavis/book-of-examples/blob/main/gallery/roc/layout.roc
Also note that I'm checking prior if the list is empty:
if List.len items == 0 then {
row: {
items: List.map currentRowItems \galleryItem -> {}, # Produces layout items from gallery items.
offsetY: 0,
height: targetRowHeight,
width,
headings
},
removedItems,
remainingItems: []
}
else
item = List.first items
aspectRatio = item.width / item.height
...
}
List.first
will always return a result.
So you should just use when List.first ... is
directly
That will check if the list is empty and return an error if so.
Then you can move your empty list logic there.
So I can't just capture the first item in the list then use it?
Do I have to unpack it from the "result" somehow?
I haven't used Result yet.
Roc will always do a bounds check and return a result.
You could match on the result and crash
in the error case if you know it is impossible, but it is definitely advised to use List.first
as your "is empty" check instead.
So the suggested way to write your code above would be something like:
when List.first items is
Ok item ->
aspectRatio = item.width / item.height
...
Err ListWasEmpty ->
{
row: {
items: List.map currentRowItems \galleryItem -> {}, # Produces layout items from gallery items.
offsetY: 0,
height: targetRowHeight,
width,
headings
},
removedItems,
remainingItems: []
}
Thanks so much.
Last updated: Jul 06 2025 at 12:14 UTC