[Haskell-cafe] Odd lack of laziness

Thomas Conway drtomc at gmail.com
Sat Jun 23 07:20:04 EDT 2007

On 6/23/07, Chaddaï Fouché <chaddai.fouche at gmail.com> wrote:

> isLength1 [x] = "Ok"
> isLength _ = "Nok"


> How is [x] big in any way ? If you need to test for more than one
> element you can just put put a guard with length

Invoking length is more strict than is necessary, though this may not
be a problem. If you want a lazier solution, you could try:

hasLength 0 [] = True
hasLength 0 (_:_) = False
hasLength n [] = False
hasLength n (_:rest) = hasLength (n - 1) rest

This only evaluates at most enough of the list skeleton to verify
whether or not it has the right length, where invoking length would
evaluate the whole list skeleton.

Dr Thomas Conway
drtomc at gmail.com

Silence is the perfectest herald of joy:
I were but little happy, if I could say how much.

More information about the Haskell-Cafe mailing list