Amjad
Amjad

Reputation: 1687

Counting elements in a list (haskell)

this is a small part of my homework, i have to count the elements of a list and if the count == 2 then return true. the elements of that list are not fixed but are filtered using a different function for example allNumbers. I have to use this existing function to check if it has 2 elements or not.

the definition of the checking function would be:

isTrue :: Int -> Bool

I have a current function defined

divisors :: Int -> [Int]
divisors n | n < 1 = []
           | otherwise = filter (\k -> n `mod` k == 0) [1..n] 

What this does is lists all numbers that divide n. now I need to make another function isTrue in the same program that will give true if the list that is produced by the above function has only two numbers.

Upvotes: 0

Views: 5273

Answers (3)

phimuemue
phimuemue

Reputation: 35983

As far as I understand, you need a function taking a list and returning a boolean value. Thus, the signature should be something like:

doit :: [a] -> Bool

doit (x:y:z) = True -- matches if the list contains at least 2 elements
doit _ = False      -- matches otherwise (i.e. list has 0 or 1 element)

-- or, we match only if the length is exactly 2

newdoit :: [a] -> Bool
newdoit [a,b] = True
newdoit _ = False

-- or even more elegant
simpledoit l = (length l)==2

-- the complete function is then e.g.
completefunc l = newdoit (divisors l)

Upvotes: 7

Frerich Raabe
Frerich Raabe

Reputation: 94329

I don't want to give away the whole solution, but I think it's worth pointing out that besides going for some solution which uses the length function to compute the length of the list and then yielding an appropriate result, you could also consider to use pattern matching here, because the length you compare with (2) is pretty small. So something like

hasLengthOfTwo <pattern_matching_lists_with_two_elements> = True
hasLengthOfTwo _ = False

A small (probably irrelevant) advantage of this is that it also works on infinite lists.

Upvotes: 5

0xAX
0xAX

Reputation: 21817

length' xs = case ((length xs) > 2) of
                  True -> True
                  _ -> False

Upvotes: 0

Related Questions