[Haskell-beginners] type error in sub-function

roman at czyborra.com roman at czyborra.com
Sun Feb 16 07:33:23 UTC 2014


> write a simple function to determine the divisors of an integer.

straight simple first, let { divides n x = (mod n) x == 0 ; divisors n = 
filter (divides n) [1..n] } in map divisors [255,256,257]

> divisors x = 1 : lower ++ upper ++ x : []
>     where lower = filter (\y -> mod x y == 0) [2..(ceiling . sqrt) x]
>           upper = sort $ map (div x) lower

time-critical millions:  let { divides n x = (mod n) x == 0; divisors n = 
let { firsthalf = filter (divides n) [ 1 .. ceiling$sqrt$fromInteger n ] } 
in nub ( firsthalf ++ map (div n) (reverse firsthalf) ) } in divisors 256


More information about the Beginners mailing list