简体   繁体   English

Haskell调用函数onload

[英]Haskell call function onload

Good morning fellow programmers! 各位程序员早上好!

i'm working on a project using haskell, and i've wanted to know how to run a haskell function without having to type two lines on ghci, for example 我正在使用haskell进行项目,我想知道如何运行haskell函数而不必在ghci上键入两行,例如

ghci filename.hs function

This can only be done doing: 这只能做:

 ghci filename.hs
function

???? ???? I'm looking for something like the main () in C,which runs automatically when you compile the program Is there something like that? 我正在寻找像C中的main(),它在编译程序时自动运行是否有类似的东西? I've been checking the -e option on ghci, but i cant seem to get it to work! 我一直在检查ghci上的-e选项,但我似乎无法让它工作!

Thank you very much! 非常感谢你!

Cheers! 干杯!

You're probably looking for ghc -e instead: 你可能正在寻找ghc -e

> echo 'foo x y z = x+y*z' > foo.hs  % let's make a foo.hs file
> ghc foo.hs -e 'foo 1 2 3'          % call the function in foo.hs
=> 7

Also, note that you can also use the :reload command in ghci. 另请注意,您还可以在ghci中使用:reload命令。 Load the file in ghci, edit, type :reload and test again. 在ghci中加载文件,编辑,键入:reload并再次测试。 Also, if this seems too tedious, you can also define a ghci macro which allows you to reload and test your function at the same time: 此外,如果这看起来太单调乏味,您还可以定义一个ghci宏,它允许您同时重新加载和测试您的函数:

> :def test \x -> return (":reload\n" ++ x)
> :test foo 1 2 3
=> Ok, modules loaded: Foo.
7

If you're looking to build real programs instead of quickly testing your functions, then you'd better read the other answers on writing main functions. 如果您正在寻找构建真实程序而不是快速测试您的函数,那么您最好在编写main函数时阅读其他答案。

I assume function has the type IO () . 我假设function的类型为IO () Then you can just let main = function , and use for example runhaskell modulename from the command line. 然后你可以让main = function ,并runhaskell modulename使用例如runhaskell modulename As in C, main is a special function. 和C一样, main是一个特殊功能。

To clarify a bit, just in case: If your function is a pure one, ie one whose type does not invovle IO , you can't really "run it". 为了澄清一点,以防万一:如果你的function是一个纯function ,即一个类型没有调用IO函数,你就不能真正“运行它”。 I guess it's a simplification to say this, but essentially what GHCi does is to call print function . 我想这是一个简化说法,但GHCi所做的基本上是调用print function If you want to mimic this, you can use something like main = print function and use runhaskell . 如果你想模仿它,你可以使用main = print function类的东西并使用runhaskell This assumes function 's type is an instance of Show . 假设function的类型是Show一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM