Haskell 代码找出一个数字的合成

Peđ*_*zić -2 haskell program-entry-point module

这是一个 Haskell 代码,用于计算一个不起作用的数字的合成。合数 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)
Run Code Online (Sandbox Code Playgroud)

我试图用命令编译这段代码:

ghc -O2 -fllvm compositorial.hs
Run Code Online (Sandbox Code Playgroud)

并得到以下编译错误:

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

compositorial.hs:38:1: parse error on input ‘module’
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 5

使用 GHC,单独的模块必须放在单独的文件中。此外,除了 之外Main,模块名和文件名必须匹配:模块Foo.Bar.Baz必须驻留在Foo/Bar/Baz.hs.

  • @PeđaTerzić 单独的问题是解决单独问题的方法(即使它们源于相同的代码库)。不要忘记最小化重现问题所需的代码——这个过程甚至可以让您了解如何自行修复它。 (3认同)