bash - 有没有办法编写 ghci session 脚本?

标签 bash haskell ghci

我的目标是通过管道将 ghci 的一些步骤从 bash 脚本运行,然后干净地退出。评论在线says为此使用runhaskell

这是 command我正在尝试运行:

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>

看来我不能使用 runhaskell 方法来盲目执行 ghci 输入。

现在解决这个问题的方法是向传递给 runhaskell 的文件添加额外的命令:

main = do print (random (mkStdGen 100) :: (Int, StdGen))

我的目标是为我正在使用的 haskell 类(class)自动运行 ghci 工作。我希望能够从 bash 脚本运行 ghci 命令——以 ghci 期望的格式,并让它干净地退出 ghci(或运行它的任何东西)。

我的问题是:有没有办法编写 ghci session 脚本?

最佳答案

您需要使用 expect为此,它允许您使用简单的命令以交互方式控制 REPL。这个脚本做你想做的:

#!/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

运行它会得到以下结果:

$ ./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 中设置提示。

关于bash - 有没有办法编写 ghci session 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735327/

相关文章:

python - 访问共享网络驱动器和删除特定文件的最佳方法

haskell - 在 Haskell 中删除具有特定 Int 的树叶

haskell - typeOf 带有类型构造函数 *->*/从程序中打印值的类型

haskell - 使用 Haskell 将数字拆分为数字

haskell - Hoogle 和 yesod - 如何轻松查找非默认包中的函数

haskell - 在 haskell 中查找类型同义词

linux - 将 ls -R 输出解析为 Unix 中的变量

linux - 创建了一个包含零的 100 字节文件。但我看不到零

bash - 使用 JSON 文件的名称及其在 bash 中的内容创建一个 JSON 对象

Haskell 模式匹配隐式类型