Home > Blockchain >  How can I check if my index is out of range of the array?
How can I check if my index is out of range of the array?

Time:08-30

I am currently a newbie just starting out.

My code :

atIndex :: [a] -> Int -> a
atIndex [] _ = error "error"
atIndex (xs) n = head (drop n xs)

The first argument is my array and the second my index (ex: atIndex [1,2,3] 1; I will get 2).

I want to know how can I send an error or message if my index is out of range of the array ?

example: atIndex [1,2,3] -1 or atIndex [1,2,3] 3 and get "error, your index is out of range".

CodePudding user response:

You can work with a guard so:

atIndex :: [a] -> Int -> a
atIndex [] _ = error "error"
atIndex (x:_) 0 = …
atIndex (_:xs) n
  | n < 0 = …
  | otherwise = atIndex … …

In Haskell, one howeve usually does not work with errors, but encodes it in the output, by using a Maybe a or Either String a type for example where Nothing/Left "error message" is used if the input is invalid, and Just x/Right x in case the input is valid with x the result wrapped in a Just or Right, so:

atIndex :: [a] -> Int -> Maybe a
atIndex [] _ = Nothing
atIndex (x:_) 0 = Just …
atIndex (_:xs) n
  | n < 0 = Nothing
  | otherwise = atIndex … …

CodePudding user response:

For variety, this is what the code looks like when using if / else and Either.

Note 1. When using guards you don't have = in the declaration, whereas you do with if / else.

Note 2. As with Maybe, where the return type is Just value or Nothing, with Either the return type is Left error or Right value. Unlike Maybe, Either includes an error message.

atIndex :: [a] -> Int -> Either String a
atIndex [] _ = Left "Error"
atIndex xs n = 
    if n >=0 && n < length(xs) then
        Right $ head (drop n xs)
    else
        Left "Error"
  • Related