user2876457
user2876457

Reputation: 47

Struggling with lists of lists in Haskell

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

Upvotes: 0

Views: 141

Answers (2)

Odomontois
Odomontois

Reputation: 16308

Just for fun - one liner

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

Upvotes: 0

twinlakes
twinlakes

Reputation: 10228

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

Upvotes: 2

Related Questions