简体   繁体   中英

Haskell code to finding out the compositorial of a number

Here is a Haskell code for computing the compositorial of a number that doesn't work. The compositorial of a composite number n is the product of all composite numbers up to and including n. What is wrong with this code?

module Compositorial where

import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.Base

-- multiply all composite numbers <= n
-- Use a sieve for a fast compositeness test, and multiply in a tree-like fashion
compositorial :: Int -> Integer
compositorial n = treeProd (sieve n) 4 n

-- Sieve of Eratosthenes, basic
sieve :: Int -> UArray Int Bool
sieve end = runSTUArray $ do
    ar <- newArray (0,end) False
    let mark step idx
            | idx > end = return ()
            | otherwise = unsafeWrite ar idx True >> mark step (idx+step)
        sift p
            | p*p > end = return ar
            | otherwise = do
                c <- unsafeRead ar p
                if c then return () else mark (2*p) (p*p)
                sift (p+2)
    mark 2 4
    sift 3

-- The meat of it, tree product
-- For larger ranges, split roughly in half and recur,
-- for short ranges multiply directly
treeProd :: UArray Int Bool -> Int -> Int -> Integer
treeProd ar low high = go low high
  where
    go lo hi
        | lo + 4 < hi = let m = (hi + lo) `quot` 2 in (go lo m) * (go (m+1) hi)
        | otherwise   = product [fromIntegral n | n <- [lo .. hi], ar `unsafeAt` n]

module Main where

import Compositorial

main = do
    print "Start"

    putStrLn "Enter a number"
    input <- getLine
    let n = (read input :: Int) 

    print $ compositorial (n)

I tried to compile this code with command:

ghc -O2 -fllvm compositorial.hs

And got the following compiling error:

[1 of 1] Compiling Compositorial    ( compositorial.hs, compositorial.o )

compositorial.hs:38:1: parse error on input ‘module’

With GHC, separate modules must go in separate files. Additionally, with the exception of Main , the module name and file name must match: module Foo.Bar.Baz must reside in Foo/Bar/Baz.hs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM