Created
January 27, 2019 02:56
-
-
Save aratama/70350bca2a2b2e98a15bb90e081a8bdd to your computer and use it in GitHub Desktop.
Fibonacchi number with ST Monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude | |
import Effect (Effect) | |
import Effect.Console (logShow) | |
import Control.Monad.ST (run, for) | |
import Data.Array.ST.Partial (peek) | |
import Data.Array.ST (thaw, push) | |
import Partial.Unsafe (unsafePartial) | |
fibo :: Int -> Int | |
fibo n = unsafePartial $ run do | |
arr <- thaw [0, 1] | |
-- 2からnまでfor文で繰り返す。 | |
for 2 (n + 1) \i -> do | |
-- 配列に継ぎ足すのは、 | |
-- 1つ前の数値と2つ前の数値を足したもの。 | |
lhs <- peek (i - 1) arr | |
rhs <- peek (i - 2) arr | |
push (lhs + rhs) arr | |
peek n arr | |
main :: Effect Unit | |
main = do | |
logShow (fibo 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment