我的目标是让ghci从bash脚本中运行一些步骤,然后干净地退出。在线评论他说使用runhaskell实现这一点。
这是我试图运行的命令:
ghci> import System.Random
ghci> random (mkStdGen 100) :: (Int, StdGen) 预期结果类似于:
(-3633736515773289454,693699796 2103410263)当我将其放入文件randomtest.hs并使用runhaskell执行它时,将得到以下错误:
randomtest.hs:3:1: error:
Invalid type signature: random (mkStdGen 100) :: ...
Should be of form <variable> :: <type>我需要一点提示才能朝正确的方向走。
我的问题是:为什么ghci的行为与runHaskell不同?
发布于 2017-12-09 00:14:06
ghci是一个REPL (Read,Eval,Print循环)。然而,runhaskell几乎等同于将程序编译成可执行文件,然后运行它。GHCI允许我们运行单个函数和任意表达式,而runhaskell只调用主函数并解释文件,而不是编译它并运行它。
正如@AJFarmar所指出的,GHCI最好用于调试和测试您正在构建的程序,而runhaskell是一种不用编译就可以运行整个程序的好方法。
所以,要解决你的问题,我们只需要给程序一个主要的功能。ghci对每个表达式的结果调用print,该表达式是在解释器中键入的,而不是绑定到变量的。
因此,我们的主要功能可以是:
main = print (random (mkStdGen 100) :: (Int, StdGen))
我们仍然需要导入System.Random,所以整个文件变成:
import System.Random
main = print (random (mkStdGen 100) :: (Int, StdGen))然后,我们可以按预期运行:
[~]λ runhaskell randomtest.hs
(-3633736515773289454,693699796 2103410263)如果我们想要从runhaskell中添加多个命令,我们只需在main中将更多的命令添加到do块:
import System.Random
main = do
print (random (mkStdGen 100) :: (Int, StdGen))
let x = 5 * 5
print x
putStrLn "Hello world!"https://stackoverflow.com/questions/47723885
复制相似问题