I'm trying to get the index of an element in a list given its Id. This is what I have:
type alias Id = Int
posInList : Id -> List (Id, ItemModel) -> Int
posInList id list =
if List.isEmpty list then
-1
else
if (List.head list).fst == id then
0
else
if posInList id (List.tail list) == -1 then
-1
else
posInList id (List.tail list) + 1
I got that from scheme-code found here (answer with 7 votes).
When I compile the code I get two errors:
How do I solve this? Or is there a simpler solution?
Update: tried it with Maybe
posInList : Id -> Maybe List (Id, ItemModel) -> Int
posInList id list =
case list of
Nothing -> -1
Just a ->
case (List.head a) of
Just b ->
if b.fst == id then
0
else
case (List.tail a) of
Nothing -> -1
Just c -> (posInList id (Just c)) + 1
Nothing -> -1
I think I'm close but I can't resolve this error:
Just c
is of type Maybe List
but where does that conflict with Maybe
?
I thought the type annotation so I added brackets like so:
posInList : Id -> Maybe (List (Id, ItemModel)) -> Int
But then I get:
And now I'm clueless, never seen an error like that.