Tom Blake
Tom Blake

Reputation: 11

Finding the number of elements in a matrix

I'm a Haskell newcomer, so cut me a bit of slack :P

I need to write a Haskell function that goes through a matrix and outputs a list of all matching elements to a given element (like using filter) and then matches the list against another to check if they are the same.

checkMatrix :: Matrix a -> a -> [a] -> Bool 

I have tried variations of using filter, and using the !! operator and I can't figure it out. I don't really want to get the answer handed to me, just need some pointers for getting me on the right path

checkMatrix :: Matrix a -> a -> [a] -> Bool 
checkMatrix matr a lst = case matr of
    x:xs | [] -> (i don't really know what to put for the base case)
         | filter (== True) (x:xs !! 0) -> checkMatrix xs a lst

Thats all i got, I'm really very lost as to what to do next

Upvotes: 0

Views: 121

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

tl;dr You want something to the effect of filter someCondition (toList matrix) == otherList, with minor details varying depending on your matrix type and your specific needs.

The Full Answer

I don't know what Matrix type you're using, but the approach is going to be similar for any reasonably defined matrix type.

For this answer, I'll assume you're using the Data.Matrix class from the package on Hackage called matrix.

You are right to think you should use filter. Thinking functionally, you want to eliminate some elements from the matrix and keep others, based on a condition. However, a matrix does not provide a natural way to perform filter on it, as the idea is not really well-defined. So, instead, we want to extract the elements from our matrix into a list first. The matrix package provides the following function, which does just that.

toList :: Matrix a -> [a]

Once you have a list representation, you can very easily use filter to get the elements that you want.

A few caveats and notes.

  • If the matrix package that you're using doesn't define toList itself, check if it defines a Foldable instance for the matrix type. If it does, then Data.Foldable has a general-purpose toList that works for all Foldable types.
  • Be careful with the ordering here. It's not entirely clear what order the elements should be put into the list in, since matrices are two-dimensional and lists are inherently one-dimensional. If the ordering matters for whatever you're doing, you might have to put some additional effort into guaranteeing the desired order. If it does not matter, consider using Data.Set or some other unordered collection instead of lists.
  • I don't see any constraints in your checkMatrix implementation. Remember that comparing elements of lists adds an Eq a constraint, and if you want to use an unordered collection then that's going to add Ord a instead.

Upvotes: 1

Related Questions