For five years running, I’ve been solving at least the first few days of Advent of Code in Haskell’s type system. It’s a fun little tradition. However, my solutions all had a lingering problem.
Let’s say this is our puzzle input:
abc
123
XYZ
To get this input into Haskell’s type system as a
Symbol, I’d reformat the input manually, inserting
\n characters like this:
type Input = "abc\n123\nXYZ\n"It’d be nicer to read the file directly, avoiding some manual input-massaging work. This is actually pretty easy to fix, with some Template Haskell.
Let’s turn on TemplateHaskell and create a
FileAsInputType module.
{-# LANGUAGE TemplateHaskell #-}
module FileAsInputType (fileAsInputType) where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (addDependentFile)We’ll write a fileAsInputType function that takes a file
path and produces a single type Input = ... declaration,
using the file’s contents. addDependentFile lets GHC know
to recompile if the input file is updated. TySynD is a type
synonym declaration, and StrTyLit is a type-level string
literal.
fileAsInputType :: FilePath -> Q [Dec]
fileAsInputType path = do
addDependentFile path
contents <- runIO $ readFile path
pure [TySynD (mkName "Input") [] (LitT $ StrTyLit contents)]Then, this Template Haskell splice…
fileAsInputType "input.txt"…will inject the file’s contents at compile time, resulting in a
useful Input type synonym we can use to refer to them.
type Input = "abc\n123\nXYZ\n"