2008/07/20

IO Monad

我終於克服對於 (IO) monad 的恐懼,開始能夠寫簡單的 Haskell programs with IO 了 XD。以下是一段 GHCi 的 session,亂數產生長 100 的 list,測試 insertion sort:

Prelude> :module System.Random
Prelude System.Random> let split f g x = (f x, g x)
Prelude System.Random> let cross f g = split (f . fst) (g . snd)
Prelude System.Random> let randomList n g = if n == 0 then ([], g) else let (x, 
g') = next g in cross (x:) id $ randomList (n - 1) g'
Loading package old-locale-1.0.0.0 ... linking ... done.
Loading package old-time-1.0.0.0 ... linking ... done.
Loading package random-1.0.0.0 ... linking ... done.
Prelude System.Random> let insert x xs = case xs of [] -> [x]; y : ys -> if x <= 
y then x : y : ys else y : insert x ys
Prelude System.Random> do {xs <- newStdGen >>= return . map (`mod` 100) . fst . 
randomList 100; print $ foldr insert [] xs}
[0,0,2,6,6,7,7,8,8,9,11,12,13,13,13,13,14,15,17,18,19,19,21,21,23,25,25,25,27,28
,33,33,34,34,35,35,35,35,37,38,39,43,44,44,45,45,46,46,47,47,48,49,50,51,53,55,5
6,56,58,58,60,61,62,62,63,63,64,65,65,66,67,67,69,70,71,73,75,75,77,78,80,81,81,
82,83,83,86,87,89,90,92,92,92,92,94,95,96,96,97,99]

--
馬上要面對的就是 Haskell 的一大堆 libraries XD。


寫成一串好像比較好看 XD:

Prelude System.Random> newStdGen >>= print . foldr insert [] . map (`mod` 100) .
 fst . randomList 100
[0,1,2,5,6,9,9,12,12,12,12,13,13,13,15,17,21,22,23,24,25,28,29,29,30,31,32,33,34
,34,36,36,36,39,42,43,44,44,46,46,48,48,48,51,52,53,53,53,54,54,55,57,58,58,60,6
1,61,62,63,65,67,67,68,68,68,69,70,70,70,70,71,72,74,74,74,74,75,76,76,77,78,80,
80,80,80,82,87,87,87,88,93,93,94,94,94,94,94,95,97,99]

Labels:

Blogger yen37/20/2008 10:42 am 說:

竟然有Open GL 也有 XHTML

好先進耶~

 

<< 回到主頁