使用 runST 解决斐波那契问题

using runST for Fibonacci issues

提问人:dilan_s 提问时间:1/4/2021 更新时间:1/4/2021 访问量:71

问:

我定义了以下内容

import Data.STRef

fib' :: Int -> Integer
fib' n = runST $ do
                 rx <- newSTRef 0
                 ry <- newSTRef 1
                 let loop 0 = do
                            x <- readSTRef rx
                            return x
                     loop n = do
                            x <- readSTRef rx
                            y <- readSTRef ry
                            writeSTRef rx y
                            writeSTRef ry (x + y)
                            loop (n - 1)
                 loop n

但是,当我尝试使用 ghci 编译代码时,出现以下错误:

    Variable not in scope: runST :: GHC.ST.ST s0 Integer -> Integer
   |
11 | fib' n = runST $ do
   |          ^^^^^

我不知道我哪里出错了,我对在 haskell 中使用可变引用很陌生,所以任何帮助将不胜感激

哈斯克尔 可变

评论

2赞 willeM_ Van Onsem 1/4/2021
您没有导入 .runST
1赞 willeM_ Van Onsem 1/4/2021
"我对在 haskell 中使用可变引用很陌生“:很少使用可变引用。
0赞 dilan_s 1/4/2021
如何导入?我以为我用 import Data.STRef 做到了
3赞 willeM_ Van Onsem 1/4/2021
不,例如,您可以使用 .import Control.Monad.ST(runST)
0赞 dilan_s 1/4/2021
是的,修复了它,谢谢

答:

2赞 dilan_s 1/4/2021 #1

答案是添加

import Control.Monad.ST(runST)

因为这个模块是必需的