27

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.

4 Answers 4

25

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"
Sign up to request clarification or add additional context in comments.

Comments

12

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.

3 Comments

Just tried this out and it seems to run super hella slow compared to ghc -e, I wonder why that is? main = print "Hello" | runhaskell took 1.371s when I benchmarked it with time, compared to ghc -e '"Hello"' took .207s
using ghc -e also loads .ghci config but runhaskell doesn't.
Gotcha, I think most of the time I'd be looking for ghc -e, but it's nice to know that I can do multi-lines if I need to with runhaskell (eg echo 'helloWorld = print "Hello World"; main = helloWorld' | runhaskell)
10

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.)

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.