有没有办法编写ghci会话脚本? [英] Is there a way to script a ghci session?
问题描述
我的目标是通过一些步骤使 ghci
从bash脚本运行,然后干净地退出.在线评论说为此使用 runhaskell
.
My goal is to pipe some steps for ghci
to run from a bash script and then exit cleanly. The commentary online says to use runhaskell
for this.
这是我要运行的命令:
ghci> import System.Random
ghci> random (mkStdGen 100) :: (Int, StdGen)
预期结果类似于:
(-3633736515773289454,693699796 2103410263)
当我将其放入文件 randomtest.hs
并使用 runhaskell
执行该文件时,出现以下错误:.
When I drop this into a file randomtest.hs
and execute it with runhaskell
I get the following error:.
randomtest.hs:3:1: error:
Invalid type signature: random (mkStdGen 100) :: ...
Should be of form <variable> :: <type>
似乎我不能使用 runhaskell
方法盲目执行 ghci
输入.
It seems I can't use the runhaskell
method to blindly execute ghci
inputs.
现在解决此问题的方法是向传递给 runhaskell
的文件中添加额外的命令:
Now the way to work around this is to add extra commands to the file that is passed to runhaskell
:
main = do print (random (mkStdGen 100) :: (Int, StdGen))
我的目标是针对我正在使用的haskell课程自动执行ghci工作.我希望能够从bash脚本中运行ghci命令-以ghci期望的格式运行,并使其从ghci干净退出(或运行它的任何方式).
My goal is to automate the running of ghci work for a haskell course I'm using. I want to be able to run the ghci command from a bash script - in the format that ghci expects, and have it cleanly exit from ghci (or whatever runs it).
我的问题是:是否可以编写ghci会话脚本?
推荐答案
您将要使用期望,您可以使用简单的命令以交互方式控制REPL.该脚本可以满足您的要求:
You'll want to use expect for that, it allows you to interactively control a REPL with simple commands. This script does what you want:
#!/usr/bin/env expect
log_user 0
spawn ghci
log_user 1
expect ".*> "
send ":set prompt \"ghci> \"\n"
expect "ghci> "
send "import System.Random\n"
expect "ghci> "
send "random (mkStdGen 100) :: (Int, StdGen)\n"
interact
运行此操作将为您提供以下内容:
Running this gives you the following:
$ ./ghci-interactive
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Prelude> :set prompt "ghci> "
ghci> import System.Random
ghci> random (mkStdGen 100) :: (Int, StdGen)
(-3633736515773289454,693699796 2103410263)
ghci>
注意:您可能需要对此进行一些调整,以防止用户在〜/.ghci
中设置提示.
Note: You might need to adjust this a bit to be resistant to users setting the prompt in ~/.ghci
.
这篇关于有没有办法编写ghci会话脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!