Newacct 的回答表明了这一点:
fractal c n = take n $ iterate (\z -> z^2 + c) c
Iterate
生成重复应用程序的无限列表。前任:
iterate (2*) 1 == [1, 2, 4, 8, 16, 32, ...]
关于 IO,您必须进行一些单子计算。
import Data.Complex
import Control.Monad
fractal c n = take n $ iterate (\z -> z^2 + c) c
main :: IO ()
main = do
-- Print and read (you could even omit the type signatures here)
putStr "Seed: "
c <- readLn :: IO (Complex Double)
putStr "Number of iterations: "
n <- readLn :: IO Int
-- Working with each element the result list
forM_ (fractal c n) $ \current -> do
putStrLn $ show current
putStrLn $ "Magnitude: " ++ (show $ magnitude current)
由于 Complex 默认情况下可与字符串相互转换,因此您可以使用readLn
从控制台读取它们(格式为Re :+ Im
)。
编辑:只是为了好玩,可以对单子语法和类型签名进行脱糖,这会将整个程序压缩为:
main =
(putStr "Seed: ") >> readLn >>= \c ->
(putStr "Number of iterations: ") >> readLn >>= \n ->
forM_ (take n $ iterate (\z -> z^2 + c) c) $ \current ->
putStrLn $ show current ++ "\nMagnitude: " ++ (show $ magnitude current)
编辑#2:一些与绘图和 Mandelbrot 集相关的链接。