这里是Haskell代码,用于计算无效的数字的组合。合成数字n的合成是所有合成数字直至n包括n的乘积。此代码有什么问题?
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)
我尝试使用命令编译此代码:
ghc -O2 -fllvm compositorial.hs
并收到以下编译错误:
[1 of 1] Compiling Compositorial ( compositorial.hs, compositorial.o )
compositorial.hs:38:1: parse error on input ‘module’
对于GHC,单独的模块必须放在单独的文件中。另外,除了Main
之外,模块名称和文件名必须匹配:模块Foo.Bar.Baz
必须位于Foo/Bar/Baz.hs
中。