What kind of optimizations does Haskell do here? -



What kind of optimizations does Haskell do here? -

so, i'm admittedly haskell newbie, far lot since i've been on prime number splurge lately. (which turned me on it)

i've got relatively basic script. works should, if it's not efficient possible. that's not question though. here script:

import system.environment oddfactors p = [x | x<- [3,5..floor (sqrt (fromintegral p))], p `mod` x == 0] prime x = oddfactors (2^x -1) == [] main = args <- getargs print (prime (read (head args) :: int))

like said, simple. oddfactors goes through odd numbers 3 sqrt(p) , adds list if factor of p.

primes calls oddfactors on 2^x -1 , checks if resulting list equal empty list.

the weird thing is, appears optimized. in case of primes if do, example, 61, programme takes 49 seconds run , returns true. if 60 or 62, though, takes .005s run , returns false. these right homecoming values, i'm curious if it's optimized somehow since knows it's looking list matching [] , after finding one, returns false, since list never []

long winded question, i'm willing take suggestions on code far. picked haskell 2 hours ago, nice :)

edit: of course of study know can utilize improve primality test, such miller-rabin, that's not point ;)

the test list == [] evaluate list much needed check emptiness of list. technically, much needed find outermost constructor of list (which : or []), bringing list weak head normal form (whnf).

for instance, (error "hello" : error "world") == [] homecoming false without evaluating error expressions.

this results expressions beingness lazily evaluated , definition of (==) using pattern matching in natural way:

[] == [] = true [] == _ = false _ == [] = false (x:xs) == (y:ys) = x==y && xs==ys

by comparison, if definition had been

[] == [] = true [] == (y:ys) = []==ys && false (x:xs) == [] = xs==[] && false (x:xs) == (y:ys) = x==y && xs==ys

then list == [] have forced computation of whole list before returning false (or, more precisely, whole list spine).

haskell

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -