0

Can anybody help me with this function?

 getCell :: [[Int]] -> Int -> Int -> Int  

Where m i j are the indexes of the lines and the columns of the list of lists m. the indexes start from zero and every line is the same size. The function should return -1 if i or j are not valid.

I'm having an exam on Haskell, and despite the fact that this might show up, i still want to know how can i do it, and because i've never worked with lists of lists in Haskell, i have no idea how to start solving this problem. Can you give me a hand ?

here's what i've done so far:

getCell :: [[Int]] -> Int -> Int -> Int
getCell [] _ _ = "the list is empty!"
getCell zs x y =
    if x > length zs || y > length (z:zs)  then -1 else
        let row = [x| x == !! head z <- zs]
            column = ...

I don't know how to find the rows and the columns

1
  • Do you know about the Maybe monad? - it is usually used in haskell-land to avoid magic values like -1 in this case. Commented Jan 19, 2014 at 23:45

2 Answers 2

2

This should work using the (!!) operator. First check if index is in the list, then access the element at that index using (!!).

getCell m i j = if i >= length m then -1
                else let
                         m0 = m !! i
                     in if j >= length m0 then -1
                        else m0 !! j
Sign up to request clarification or add additional context in comments.

Comments

0

Just for fun - one liner

getCell l i j = (((l ++ repeat []) !! i) ++ repeat (-1)) !! j 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.