Export code samples AND display verbatim

I'd like to write a LaTeX document with code samples in a verbatim environment. I'd also like to export those code samples to named files so that they can be built and run. This allows me to easily run tests on my code samples to make sure my document doesn't contain buggy code. So I'd like to write LaTeX like this

\begin{code}[test1.hs]
main = do
print "Hello, world!"
\end{code}


and have that code sample appear both in my document verbatim and, as a side effect, in the file test1.hs.

Unfortunately, my attempts to write LaTeX to both display code verbatim and output code to a file have ended up with me tying myself in knots. Is there an easy way to do this?

• just write to a file using filecontents or similar, then you can \input and \verbatiminput the file to show it in both forms (or simpler actually write the examples in separate files to start with) – David Carlisle Feb 18 '18 at 20:38
• That doesn't seem to help. LaTeX like this fails in pretty much the same way as my attempts to use a verbatim environment \newenvironment{code}{ \begin{filecontents}{test.cpp} } { \end{filecontents} \VerbatimInput{test.cpp} } – user207442 Feb 18 '18 at 21:51
• you can not use verbatim commands in another enviornment, you can use a custom verbatim definition or simply use filecontents followed by verbatim input – David Carlisle Feb 18 '18 at 21:53

A possible solution with tcolorbox.

Of course, you can customize the box as you like, also without the frame.

\documentclass{book}
\usepackage{tcolorbox}
\tcbuselibrary{breakable,listings}
\newtcbinputlisting{\mylisting}[2][]{%
listing file={#2},
title=Listing of \texttt{#2},
colframe=red,fonttitle=\bfseries,
listing only,breakable, #1}

\begin{document}
This creates a file \texttt{test1.hs}:

\begin{tcbverbatimwrite}{test1.hs}
main = do
print "Hello, world!"
\end{tcbverbatimwrite}

And this use it:

\mylisting{test1.hs}
\end{document}