I've come across the following answer in a code-golf challenge in Haskell, where one has to provide a function:
<bindings>
<expression>
Now, the last line on its own is a curried expression and as such eligible. However, without the previous definitions, it won't work and results in an error. For example, the following code defines the list of Fibonacci numbers (f
) and provides an expression to get the n-th Fibonacci number:
f=0:1:zipWith(+)f(tail f)
(f!!)
This isn't valid Haskell, since top-level splices/annotations/expressions in a .hs
file are only possible with TemplateHaskell
(and it won't work if you use -XTemplateHaskell
, since that's not a valid use of TH either). It also cannot get streamed into GHCi or other interpreters with
cat File.hs | interpreter`
since you need let
to create bindings:
ghci> let f=0:1:zipWith(+)f(tail f)
The only way to create a single expression from this would be let … in
, which takes up to 7 additional bytes
let f=0:1:zipWith(+)f(tail f)in(f!!)
which can be used as anonymous function (2), but that seems an overkill to a binding, which takes just two additional bytes:
f=0:1:zipWith(+)f(tail f)
g=(f!!)
Question
Is the invalid code invalid? Or are we allowed to introduce syntax/semantic errors and dump some of the work (properly bind, change syntax, or similar) to the user?
Personal remarks
Given that answers should provide working code that just needs to get loaded/executed, I think that answers of this kind are invalid. The code cannot get loaded in Hugs/GHCi with :l
and it cannot get executed with runhaskell
, ghc -e
or similar.
However, I think that can lead to many Haskell answers needing two additional bytes.
Note that this isn't a duplicate of Unnamed Functions in Code Golf, since that question considers only syntactically valid code. One can have a expression at top-level in Python. It's an error in Haskell.
#
andt
), let's sayf.hs
and then call it likeghc -e '(filter t[1..]!!) 54' f.hs
. This even saves a byte, because you can omit one newline. \$\endgroup\$ghc -e ''
still has to be written somewhere. But that's for another question. \$\endgroup\$ghc -e ''
has to be written, but that's for free, just likeperl -e ''
for Perl. After all we provide functions as answers, not the boilerplate to call them. \$\endgroup\$public static void main(String[]args){System.out.println("Hello, World");}
in Java, but it still is a valid code-golf submission and it is in fact syntactically correct. \$\endgroup\$