Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pipe source code to GHC through standard input?

Tags:

haskell

ghc

I mean something like this:

echo 'main = print 1' | ghc > executable

To which GHC replies: ghc: no input files

Am I missing something? Is this possible somehow?

like image 991
Wizek Avatar asked Jul 10 '15 21:07

Wizek


People also ask

How do I run a program in ghci?

If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu. And you are presented with a prompt. The Haskell system now attentively awaits your input.

How do I load files into ghci?

From the command line, enter "ghci" (or "ghci -W") followed by an optional filename to load. Note: We recommend using "ghci -W", which tells GHC to output useful warning messages in more situations. These warnings help to avoid common programming errors.

How do I load a file into Haskell?

Open a command window and navigate to the directory where you want to keep your Haskell source files. Run Haskell by typing ghci or ghci MyFile. hs. (The "i" in "GHCi" stands for "interactive", as opposed to compiling and producing an executable file.)


3 Answers

This might not be what you want, but as melpomene already mentioned, runghc can do that. I think it deserves its own answer:

runghc <<< 'main = print 123'

Try it online

like image 155
stasoid Avatar answered Sep 23 '22 08:09

stasoid


Even though this isn't possible with normal process substitution, zsh provides a special kind of process substitution-like behavior that allows the "file" to act like more of a real file than traditional process substitution does (by creating an actual temporary file):

% ghc -o Main -x hs =( echo 'main = print 1' )
[1 of 1] Compiling Main             ( /tmp/zshjlS99o, /tmp/zshjlS99o.o )
Linking Main ...
% ./Main
1
% 

The -x hs option tells ghc to act as though the file name given ends in .hs.

Overall, this is essentially a shortcut around manually creating and deleting a temporary file.

I'm not sure if there are other shells that support this kind of thing. I don't think bash does, at least.

like image 29
David Young Avatar answered Sep 23 '22 08:09

David Young


Typically ghc is used as a compiler and you run it on files (on which ghc can seek and infer types from endings etc) and specify output files as flags.

You can, however, of course, use

filename=$(mktemp --suffix=.hs)
echo "main = print 1" >> $filename
ghc -o executable $filename 
like image 22
Marcus Müller Avatar answered Sep 21 '22 08:09

Marcus Müller