Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to directly invoke Haskell code from Bash and output to stdout?

Is possible to output to stdout a simple Haskell one-liner like

main = print "Hello World"

directly from Bash? Something ala php -r 'echo "Hello World\n";'

I poked around in the ghc options but I didn't see anything that would help me.

like image 457
Joe Crawfordy Avatar asked Oct 17 '14 02:10

Joe Crawfordy


4 Answers

I think I figured it out from here

$ ghc -e "interact (unlines.map reverse.lines)"
hello
olleh

UPDATE:

just did some more tests, this works too:

echo "hi" | ghc -e "interact (unlines.map reverse.lines)"
// prints "ih"
like image 111
Joe Crawfordy Avatar answered Nov 08 '22 14:11

Joe Crawfordy


Consider runhaskell command which can take piped stdin, for instance like this,

echo 'main = print "Hello World"' | runhaskell

Update

In general you can script Haskell source as follows,

#!/usr/bin/env runhaskell

main = putStrLn "Hello World"

This actually compiles and executes the program, whereas ghc -e will evaluate an expression.

like image 27
elm Avatar answered Nov 08 '22 12:11

elm


You found ghc -e yourself. Here are some useful aliases that go well with that:

function hmap { ghc -e "interact ($*)";  }
function hmapl { hmap  "unlines.($*).lines" ; }
function hmapw { hmapl "map (unwords.($*).words)" ; }

(Discussed in this old blog post of mine.)

like image 10
Joachim Breitner Avatar answered Nov 08 '22 14:11

Joachim Breitner


I wrote eddie (https://eddie.googlecode.com/) to provide more facilities than "-e". From the linked page:

Eddie adds features to make using it for shell scripting easier:

When given file arguments, eddie feeds them to your function. Eddie can easily add modules to the namespace you use. Eddie has options for processing things a line or file at a time. Eddie will use binary file IO methods when asked to.

Be warned that eddie was my first "real" haskell application, and is seriously in need of a rewrite.

like image 2
Mike William Meyer Avatar answered Nov 08 '22 13:11

Mike William Meyer