For Programmers: Free Programming Magazines  


Home > Archive > Functional > June 2006 > Newbie help: basic list comprehension









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Newbie help: basic list comprehension
Arved Sandstrom

2006-06-28, 8:03 am

I have this (essentially my first) list comprehension:

recnx n x | x^2 < 1 =
1 : -n * x : [ -b * (n-1+a) * x / a | (a,b) <- zip [2..] (tail (recnx n
x))]

It computes (1 + x) ^ -n, and seems to do the trick. That is,

> sum (take 16 (recnx 5 0.07))

0.712986179483667

and

> 1.07 ** -5

0.712986179483668

What are possible improvements in how I did it? Is there a better approach
not using a list comprehension? Also, how the hell do I supply a type for
this?

AHS


genea

2006-06-29, 4:00 am

Arved Sandstrom wrote:
> I have this (essentially my first) list comprehension:
>
> recnx n x | x^2 < 1 =
> 1 : -n * x : [ -b * (n-1+a) * x / a | (a,b) <- zip [2..] (tail (recnx n
> x))]
>
> It computes (1 + x) ^ -n, and seems to do the trick. That is,
>
> 0.712986179483667


I was able to get the same result using ghci:
Prelude> sum (take 16 (recnx 5 0.07))
0.7129861794836668 <- just didn't round off as early


> Also, how the hell do I supply a type for
> this?


Hi, Let the machines interactive compiler do the work on the
type... using ghci I got :

recnx :: forall a. (Fractional a, Enum a, Ord a) => a -> a -> [a]
by issuing the command: :t recnx

As to doing this another way.. well I am a big fan of list
comprehensions..
writing functions that are parameterized list comprehensions..
they are usually very clear and self documenting. "usually!!"
--gene

Arved Sandstrom

2006-06-30, 8:00 am

"genea" <yumagene@gmail.com> wrote in message
news:1151557748.774550.144320@b68g2000cwa.googlegroups.com...
> Arved Sandstrom wrote:
>
> I was able to get the same result using ghci:
> Prelude> sum (take 16 (recnx 5 0.07))
> 0.7129861794836668 <- just didn't round off as early


As you might expect, it approaches the solution much faster for small x. Try
x = 0.1, and you won't need 16 terms.

>
> Hi, Let the machines interactive compiler do the work on the
> type... using ghci I got :
>
> recnx :: forall a. (Fractional a, Enum a, Ord a) => a -> a -> [a]
> by issuing the command: :t recnx


Good point. I get essentially the same in Hugs.

> As to doing this another way.. well I am a big fan of list
> comprehensions..
> writing functions that are parameterized list comprehensions..
> they are usually very clear and self documenting. "usually!!"


I like list (and array) comprehensions a great deal. But you certainly don't
always need them, and I suspect that in this case you don't.

AHS


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com