0
votes

a = [ 1, 2, 3] a [1,2,3]

b = [ 3, 4, 5] b [3,4,5]

c = [a ,b] c [[1,2,3],[3,4,5]]

a !! 2 (Just 3)

a !! 2 (Just 3)

a !! 1 (Just 2)

c !! 2 Nothing

c !! 1 (Just [3,4,5])

c !! 1 !! 0 Error found: in module $PSCI at line 1, column 1 - line 1, column 11

Could not match type

Maybe

with type

Array

while trying to match type Maybe (Array Int) with type Array t0 while checking that expression (index c) 1 has type Array t0 in value declaration it

where t0 is an unknown type

1

1 Answers

4
votes

Indexing into an array returns not the plain element, but values wrapped in Maybe, because the array might not have an element at the given index. In your case, the result of c !! 1 has type Maybe (Array Int). So you have to handle that Maybe somehow.

I guess you expect the end result to be of type Maybe Int. There are different ways to do so. The perhaps most explicit one is:

case c !! 1 of
  Nothing  -> Nothing
  (Just x) -> x !! 0

(this will return Just 3)

Because "chaining" functions like this is very common, there are abstractions that lead to the same result, e.g.:

(c !! 1) >>= (_ !! 0)

Anyways, the trick is to reach into the first result (if it was successful) and then try the second indexing. If both succeed, return the end result. If one fails, return Nothing.