Hacker News new | past | comments | ask | show | jobs | submit login
π in Clojure (combinate.us)
24 points by alrex021 on Feb 12, 2010 | hide | past | favorite | 7 comments



Haskell version:

    import Data.Number.Fixed
    
    pis :: [Fixed Prec50]
    pis = map termToPi $ iterate update (1, 1/(sqrt 2), 1/4, 1)
        where update (a,b,t,p) = (a',b',t',p') 
                  where a' = (a+b)/2
                        b' = sqrt(a*b)
                        t' = t - p * sqr(a - a')
                        p' = 2 * p
              termToPi (a,b,t,_) = sqr(a + b) / (4*t)
              sqr x = x*x
    
    main = putStrLn . show $ pis !! 20
    -- 3.14159265358979323846264338327950288419716939937583
IMHO that was cleaner and easier than the Clojure code. I didn't really get the bindings thing.

Edit: Out of curiosity I checked with Debug.Trace to see how it runs, and termToPi only gets called once for the term that was requested, even though I said "map termToPi". Fun!


Couldn't Clojure also do lazy evaluation to get the same optimization?


I'm not sure, but I think Clojure would fully evaluate all terms until it gets the one you request. Clojure has lazy sequences, but it doesn't turn everything into thunks like Haskell.


The post starts so beautifully... and then the JVM shows up.


I'm amused that news.arc automatically capitalized the first letter of this post. (It also makes lots of iPhone/iPad stories look kind of weird.)


You mean why it didn't right?

If so, reason is that the first character of this post is actually a pi symbol. (c-c c-v -> editor)


I thought it had changed lowercase π to capital Π... but I see now that it was just a trick of the font. (HN appears in Verdana on my computer, and Verdana's lowercase pi looks like most typefaces' capital Pi.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: