-4

longEnough n xs: checks if a list has more than n elements.

Examples:

  • longEnough 2 [1..5] == True
  • longEnough 3 [1,2,3] == False
  • longEnough 0 [] == False
  • longEnough 20 [1..] == True
Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • 1
    See [Is there any way to separate infinite and finite lists?](http://stackoverflow.com/questions/33016410/is-there-any-way-to-separate-infinite-and-finite-lists) – effectfully Nov 02 '15 at 05:23
  • Use `foldr`. Fold over the list to produce a function taking the desired strict lower length bound. – dfeuer Nov 02 '15 at 05:39
  • 3
    What did you try? SO is not a homework solving service. On this kind of questions, the poster is often expected to show some effort. – chi Nov 02 '15 at 08:58

1 Answers1

1

I guess this is homework and you are still learning the basics so I'll start by giving you some hints using the recursion instead of foldr (as @dfeuer proposed):

First start by noting some obvious cases:

  • if xs = [] then the result is always False (assuming you don't care about negative n in some strange ways)
  • if n = 0 and xs is non-empty then it's always True
  • in all other cases you have
    • n > 0
    • xs has more than one element

Maybe you have some recursive idea to break the last case down?

Here is a skeleton:

longEnough :: Int -> [a] -> Bool
longEnough _ []     = False
longEnough 0 _      = True
longEnough n (_:xs) = let n' = (n-1) in undefined

For those cases - if you look closely you'll see that I even added more hints on the solution.


PS

  • maybe you want to think about negative n and what should happen to those ... I did not here
  • if you know what foldr is all about you should probably try to implement this using foldr too

Solution

Seems there is no more feedback coming from the OP so I guess I can as well post the solution as I would start with:

longEnough :: Int -> [a] -> Bool
longEnough _ []     = False
longEnough 0 _      = True
longEnough n (_:xs) = longEnough (n-1) xs

(Not really much left to do...)

Here are the mentioned test-cases:

λ> longEnough 2 [1..5]
True
λ> longEnough 3 [1,2,3]
False
λ> longEnough 0 []
False
λ> longEnough 20 [1..]
True
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Random Dev
  • 51,810
  • 9
  • 92
  • 119