I have the following function that acts as an index operator:
let { index :: [a]->Int->Maybe a index [] i = error "Empty list" index li = if i <= ((length l) - 1) && i >= 0 then Just(l !! i) else error "Index out of bounds" }
Now, I originally wrote this without using Just (and I still don't understand what it is after googling):
let { index :: [a]->Int->Maybe a index [] i = error "Empty list" index li = if i <= ((length l) - 1) && i >= 0 then (l !! i) else error "Index out of bounds" }
For me, this function makes sense. Because here I have a function that takes a list of "generic type" a and Int , which is an index, and returns a Maybe value of type a or throws an exception at runtime. However, I don't understand the bit where GHCi tells me this:
<interactive>:1:120: Couldn't match type `a' with `Maybe a' `a' is a rigid type variable bound by the type signature for index :: [a] -> Int -> Maybe a at <interactive>:1:34 Expected type: [Maybe a] Actual type: [a] In the first argument of `(!!)', namely `l' In the expression: (l !! i)
Now why is GHCi confused with type l and why is it expecting a list of type Maybe a ? Finally, how does Just solve the problem?
source share