関数型プログラミング言語Haskell Part15
■ このスレッドは過去ログ倉庫に格納されています
0648デフォルトの名無しさん
2011/09/16(金) 07:52:07.17手続き的に描くならモナド使うのがわかりやすいyp
関数型っぽいやりかたなら http://en.literateprograms.org/Sieve_of_Eratosthenes_%28Haskell%29
あたりみるのがいいよ
import Data.List
import Control.Monad.RWS
import Control.Monad.Identity
type SearchList = [Int]
type PrimeList = [Int]
type Max = Int
type Sieve = RWST Max PrimeList SearchList Identity
pop = do { x <- gets head ; modify tail ; return x }
square x = x * x
last' [] = Nothing
last' a@(x:xs) = Just $ last a
step :: Sieve ()
step = do {
x <- pop ; tell $ [x] -- step 2
; modify $ filter $ (/= 0) . (`mod`x) -- step 3
; y <- gets $ maybe 0 id . last' ; if square y < x then return () else step -- step 4
}
trd3 = (\ (_,_,x) -> x)
sieve m = trd3 $ runIdentity $ runRWST step m sl
where sl = [2..m] -- step 1
■ このスレッドは過去ログ倉庫に格納されています