Question About lists

Artie Gold agold@bga.com
Mon, 30 Dec 2002 13:47:37 -0600


Cesar Augusto Acosta Minoli wrote:

> Hello! I'm Working with Lists in Haskell, I´m a Beginner in Functional 
> Programming and I would like to know if there is a way to write a more 
> efficient function that return the length of a list, I wrote this one:
> 
> long        ::  [a]->Int
> long p     =  longitud p 0
>                    where
>                    longitud []       s=s
>                    longitud (x:xs) s=longitud xs (s+1)
> 
> but I think that it have a lineal grow O(n).



Sure. The only way to count the elements in a list is to, well, count 
the elements; it's an inherently linear operation.

One suggestion, though is that you're working too hard; there's really 
no reason to define a locally defined function. The much simpler:

long [] = 0
long (x:xs) = 1 + long xs

will do quite nicely.

HTH,
--ag


> 
> thanks!
> 
>  
> 
>  
> 
>  
> 
>  
> 
> 
> ------------------------------------------------------------------------
> Add photos to your e-mail with MSN 8. Get 3 months FREE*. 
> <http://g.msn.com/8HMEEN/2021> 
> _______________________________________________ Haskell mailing list 
> Haskell@haskell.org http://www.haskell.org/mailman/listinfo/haskell



-- 
Artie Gold -- Austin, Texas