Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count non-empty lists in a lists of lists

Tags:

list

haskell

I am trying to count the number of non-empty lists in a list of lists with recursive code. My goal is to write something simple like:

prod :: Num a => [a] -> a
prod [] = 1
prod (x:xs) = x * prod xs

I already have the deifniton and an idea for the edge condition:

nonEmptyCount :: [[a]] -> Int
nonEmptyCount [[]] = 0

I have no idea how to continue, any tips?

like image 574
Beszteri Avatar asked Dec 07 '25 08:12

Beszteri


2 Answers

I think your base case, can be simplified. As a base-case, we can take the empty list [], not a singleton list with an empty list. For the recursive case, we can consider (x:xs). Here we will need to make a distinction between x being an empty list, and x being a non-empty list. We can do that with pattern matching, or with guards:

nonEmptyCount :: [[a]] -> Int
nonEmptyCount [] = 0
nonEmptyCount (x:xs) = -- …

That being said, you do not need recursion at all. You can first filter your list, to omit empty lists, and then call length on that list:

nonEmptyCount :: [[a]] -> Int
nonEmptyCount = length . filter (…)

here you still need to fill in .

like image 90
Willem Van Onsem Avatar answered Dec 08 '25 21:12

Willem Van Onsem


Old fashion pattern matching should be:

import Data.List

nonEmptyCount :: [[a]] -> Int
nonEmptyCount []     = 0
nonEmptyCount (x:xs) = if null x then 1 + (nonEmptyCount xs) else nonEmptyCount xs 
like image 30
A Monad is a Monoid Avatar answered Dec 08 '25 23:12

A Monad is a Monoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!