# Tips for golfing in Haskell

What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

• Seeing the number of answers till now, I am in doubt about whether Haskell is even a good language for code golfing or not? Jan 24 '14 at 10:23
• Why only one tip per answer? Also, every language is a good language for golfing. Just don't always expect to win. Feb 12 '14 at 0:46
• @unclemeat This way people could upvote the good ones to the top without upvoting the bad ones only because they were written by the same guy in the same answer. Jun 1 '14 at 12:10
• Special request, String compression. Feb 20 '16 at 0:07
• This is probably not suited as an anwer, but I'm still want to add it here: wiki.haskell.org/Prime_numbers_miscellaneous#One-liners May 25 '16 at 19:38

A language is defined by its implementation, and lambdabot (the IRC bot over at #haskell) imports a ton of common modules by default. No need to spend precious bytes re-implementing your favorite functions from Data.List or Control.Monad, just write Haskell (Lambdabot) instead of Haskell in the title and you're good to go!

Edit:
Here's a list of stuff that it imports by default, which includes, among other things, Control.Arrow, Data.Bits, Data.Ratio, System.Random and {-# LANGUAGE ParallelListComp #-} - go wild!

## Partition a string with mapM and words

This function computes all partitions of a given string into nonempty contiguous substrings:

map(words.concat).mapM(\c->[[c],c:" "])


The idea is that the mapM non-deteministically replaces each character c with either "c" or "c ", and the resulting lists are concatenated and split at spaces. There are two gotchas: the string must not contain spaces (if it contains spaces but not line breaks, use "\n" and lines for one extra byte), and each partition occurs twice in the resulting list (with and without a trailing space, which gets eaten by words).

I've used this technique a couple of times (at least here, here and here). It's pretty flexible, since you can apply more functions after words to modify the partitions, and/or replace map with another iteration function, like any.

• Great idea using string function to split! I'll have to use this sometime. The best general-purpose alternative I found was 45 bytes, 6 longer: foldr(\h t->map([h]:)t++[(h:y):z|y:z<-t])[[]].
– xnor
Nov 4 '16 at 7:02
• When applied directly to some x this can be slightly shortened to words.concat<$>mapM(\c->[[c],c:" "])x . Apr 24 '17 at 20:44 When writing expressions that don't use variables, you don't need to include the function name for scoring purpose. For example: f=foo.bar  If f is the golfing answer, the byte count is 7 (you can omit f=). It is possible to write it properly with TIO using CPP. In the header, include: {-# LANGUAGE CPP #-} f=\  Example here. • Golfier: Add a -cpp compiler flag. Oct 31 '17 at 21:22 # Use (0<$) instead of length for comparisons

When testing if a list a is longer than a list b, one would usually write

length a>length b


However replacing each element of both lists with same value, e.g. 0, and then comparing those two lists can be shorter:

(0<$a)>(0<$b)


Try it online!

The parenthesis are needed because <$ and the comparison operators (==, >, <=, ...) have the same precedence level 4, though in some other cases they might not be needed, saving even more bytes. • I like: void a>void b Unfortunately, the generic version is not imported by default. :-( Feb 13 '20 at 22:37 # Online Tools • Try it online! TIO supports online compilation of Haskell code with the GHC 8.0.2 compiler. As TIO is developed with code golfing in mind it's not just an online interpreter but also offers features like byte count, header and footer sections that do not count towards the total byte count (put your main and test code there), automatic markdown generation for a code golf submission, and more. • pointfree.io Converts Haskell code to pointfree Haskell code which sometimes is shorter, see this tip. Note: When dealing with functions that take two or more arguments, the pointfree version generated by pointfree.io often includes the ap function which is not in Prelude. However <*> is an equivalent inline version of ap and contained in Prelude in ghc 7.10 or higher. The same goes for liftM2, which is also only available when importing Control.Monad. The pointfree version of some expression like \x -> f (g x) (h x) is given as liftM2 f g h, though this can equivalently be expressed as f.g<*>h. • Hoogle is a Haskell API search engine, which allows you to search many standard Haskell libraries by either function name, or by approximate type signature. Useful to quickly search the documentation or lookup in which packages a function is included. • Note that TIO currently uses GHC 7.8, so the stuff in this tip is not available. Jan 18 '17 at 14:05 • @Zgarb I asked Dennis if ghc can be updated. Currently one can add import Control.Applicative and/or import Control.Monad into the header on TIO to use <$> ect. Jan 18 '17 at 15:18
• @Zgarb TIO's ghc was updated to 8.0.2 thanks to Dennis. Jan 22 '17 at 20:06
• TIOv2 Alpha was replaced with a fork of TIO Nexus, so GHC8.0.2 should be supported. Jun 1 '17 at 15:38

There already are comments on pointfree code and one mentioning pure, but I figured I'd make a specific tip for this since I see it a lot.

The Applicative functions in Prelude by default when specialized to functions are as follows

instance Applicative ((->) a) where
pure = const
(f <*> g) x = f x (g x)


Note that for this particular type, (=<<) acts almost the same as (<*>), except it takes its second argument flipped (thanks @ØrjanJohansen).

pure is one character shorter than const, as mentioned elsewhere. The especially useful combinator, however, is (<*>). Below are examples of where I've used it recently.

# Unique characters

The straightforward way to solve this is

import Data.List
map(\x->(x!!0,length x)).group.sort


But we're here for codegolf, not readable code.

import Data.List
map((,).nub<*>length).group.sort


# A contrived function

This comes from a function my coworker wrote that I (unashamedly) golfed until it was unreadable.

Suppose we have

data Ex a b c
= Ex
{ foo :: [(a,b)]
, bar :: c}


and we want the natural implementation of a function

f :: Ex a b c -> [(a,c)]


I don't have the original solution (it did involve (&&&) from Control.Arrow, though), but the golfed one using (<*>) is

map.fmap.pure.bar<*>foo


which also abuses the Functor instance of (,) a.

# digitSum(n) + n

This golf is part of this answer.

This is a pretty well-golfed function

\n->n+sum[read[d]|d<-show n]


but if we do away with readability and bring in (<*>), we can shave off a character:

foldr((+).read.pure)<*>show
-- = \x -> foldr ((+) . read . pure) x (show x)


# do notation

If your function is of the form \x -> (expr) x and (expr) contains some repeated blah x often, you can sometimes save bytes with Reader monad do notation and b<-blah.

Here are some strange examples:

\x->max(div x 3*div x 5^div x 7)x   -- original expression
f x|d<-div x=max(d 3*d 5^d 7)x;f    -- define f=... then use f
\x->max(x!3*x!5^x^7)x;(!)=div       -- define (!)=div
do d<-div;max$d 3*d 5^d 7 -- aha! \x->product x:filter(/=product x)x -- original expression (:)<$>product<*>(filter=<<(/=).product) -- yeah, no...
f x|p<-product x=p:filter(/=p)x;f       -- define f=... then use f
\x->p x:filter(/=p x)x;p=product        -- define p=product
do p<-product;(p:).filter(/=p)          -- aha!


In general, do a<-b;c<-d;e is equivalent to \x->let{a=b x;c=d x}in e x.

• Using =<< instead of <*> gives a different parameter order that is sometimes useful. Jul 24 '19 at 10:14
• (<*>) is the S combinator; pure is the K combinator. Jul 24 '19 at 19:52

# Powerset

The "canonical" way of computing the powerset of a list is Data.List.subsequences. If it is used only once and applied to a value (as opposed to, say, being fed to map), it's slightly shorter to implement it yourself. Compare:

import Data.List;subsequences x
concat<$>mapM(\a->[[a],[]])x  This saves 0-3 bytes depending on whether you need a space between subsequences and the argument, and whether the latter expression needs parentheses around it. If x has the form f<$>y, you can move f inside the lambda to save some more bytes, particularly if f is also defined by a lambda:

import Data.List;subsequences$f<$>y
concat<$>mapM(\a->[[f a],[]])y import Data.List;subsequences$(\a->a*3+1)<$>y concat<$>mapM(\a->[[a*3+1],[]])y


It's also possible to compose concat with another function, if you intended to map it over the subsequences anyway:

import Data.List;g<$>subsequences x g.concat<$>mapM(\a->[[a],[]])x


If you have already imported Control.Monad, you can implement the powerset function in 18-20 bytes with one of

filterM(\_->[0>1..])
filterM$[0>1..]<$id
filterM([0>1..]<$f) filterM$[0>1..]<$f  The last two variants need another function f :: a -> b to be defined, where [a] is the type of the list (doesn't matter what f does or what b is). The optimal choice depends on whether such an f is available, and whether you need parentheses around the expression. • Might note that this gives 3 different variations in the ordering of the resulting power set. subsequences uses the order that generalizes to an infinite list, although then it's not really a power set. Jan 11 '18 at 19:26 • Maybe it has some use in some situation (\a->[[a],[]]) has the same length as the point free ((:[[]]).pure). Jun 4 '21 at 21:11 ## Cheap divisors The usual way to get the divisors (factors) of n is: [d|d<-[1..n],mod n d<1]  For example, n=6 gives [1,2,3,6]. But, if you're OK with divisors repeating out of order, you can just do: gcd n<$>[1..n]


For n=6, this gives [1,2,3,2,1,6]. The code is effectively [gcd k n|k<-[1..n]], takes the greatest common divisor of k with n. These are by definition divisors of n, and each divisor d appears at least once as gcd d n. So, the "set" of divisors is correct. The first appearances are in increasing order, so removing duplicates will match the original code's result.

# Use Data.Lists

This package defines a lot of nice functions on lists! It’s like Data.List in base, but fancier.

Importing it costs 18 bytes (import Data.Lists\n).

Here are some nice things it exports, on top of everything from Data.List:

Various shortcuts:

for              ≡ flip map
unionOf          ≡ foldr union []
hasAny e x       ≡ any (elem e) x
countElem i      ≡ length . filter (== i)
list b f xs      ≡ if null xs then b else f xs
firstOr x        ≡ list x head
maxList xs       ≡ list 0 maximum
catchNull f      ≡ list Nothing (Just . f)
lastToMaybe      ≡ catchNull last
chop f           ≡ list [] (\x->let (y,ys)=f x in y:chop f ys)
pair x y         ≡ guard (length x == length y) >> Just (zip x y)
pairWith f x y   ≡ guard (length x == length y) >> Just (zipWith f x y)

Split functions:

splitOn "x" "axbxc"                  ≡ ["a","b","c"]
endBy ";" "foo;bar;baz;"             ≡ ["foo","bar","baz"]
splitWhen (<0) [1,3,-4,5,7,-9,0,2]   ≡ [[1,3],[5,7],[0,2]]
splitOneOf ";.," "foo,bar;baz.gluk"  ≡ ["foo","bar","baz","gluk"]
endByOneOf ";.," "ae;io.,u,"         ≡ ["ae","io","","u"]
chunk 3 ['a'..'k']                   ≡ ["abc","def","ghi","jk"]
replace old new                      ≡ intercalate new . splitOn old

Variants of Data.List functions:

elemRIndex     ∷ a -> [a] -> Maybe Int   (Rightmost index)
powerslice     ∷ [a] → [[a]]             (All slices of a list)

spanList       ∷ ([a] → Bool) → [a] → ([a], [a])
breakList      ∷ ([a] → Bool) → [a] → ([a], [a])
takeWhileList  ∷ ([a] → Bool) → [a] → [a]
dropWhileList  ∷ ([a] → Bool) → [a] → [a]

Data.List.Argmax:

argmin,         argmax           ∷ Ord b ⇒ (a → b) → [a] →   a
argmins,        argmaxes         ∷ Ord b ⇒ (a → b) → [a] →  [a]
argminWithMin,  argmaxWithMax    ∷ Ord b ⇒ (a → b) → [a] → ( a,  b)
argminsWithMin, argmaxesWithMax  ∷ Ord b ⇒ (a → b) → [a] → ([a], b)

Association list functions: treat [(k, v)] as a pseudo-map type.

delFromAL l k  ≡ filter ((/= k) . fst) l
addToAL l k v  ≡ (k, v) : delFromAL l k
keysAL         ≡ map fst
hasKeyAL k     ≡ any ((== k) . fst)
flipAL         ∷ [(k, v)] → [(v, [k])]


# Use fromEnum instead of ord

fromEnum is already available in Prelude, while ord needs to be imported from Data.Char. This will save you 12 bytes. With subsequent usages you should define an alias like f=fromEnum and use f.

• If you use it more than once, you should define an alias with e=fromEnum, which is shorter than import Data.Char and costs 1 byte to use. Jan 11 '17 at 7:59
• @Zgarb: of course, I'm always doing that when writing answers, but for this tip I totally forgot about it. Jan 11 '17 at 8:15
• The same goes for chr and toEnum, however the type of toEnum needs to be forced from context. Jan 13 '17 at 16:14

# Define local variables in list comprehensions using singleton lists

For example, rather than writing

[x+y|x<-[1..5],let y=2]


one can write

[x+y|x<-[1..5],y<-[2]]


for a byte less.

This works in do blocks as well, but only in the list context since the [] syntactic sugar is necessary to come out ahead. (I guess any custom monads with single-letter constructors would benefit from this, too, but I don't think I've ever seen any of those show up in code golf.)

• @Brute_Force: I meant only to show an example of how this tip would be used; I did not mean to claim that this particular example is realistic. For a more realistic example, consider \a b->[[r..s]|r<-[a..b],s<-[2*r+7],s>7] Jul 6 '17 at 23:15

# Integral to Fractional (e.g. Int to Double)

fromIntegral :: (Integral a, Num b) => a -> b


in many cases

realToFrac :: (Real a, Fractional b) => a -> b


works too. and is two bytes shorter.

• There are cases where read.show works too, if GHC can infer the types. (For example: sin$read$show someInt.)
– Lynn
Nov 18 '17 at 14:23
• toEnum :: Enum a => Int -> a also works, though slightly more constrained. Jan 18 '19 at 7:20

# Converting to Pointfree

As @Laikoni mentioned in this post, you can use pointfree.io to convert your code to pointfree code. However, if you want to do this conversion manually you can check out this answer on stackoverflow by @luqui, which provides an algorithm:

You need the following combinators, which are in the standard library. I have also given their standard names from combinator calculus.

id :: a -> a                                   -- I
const :: a -> b -> a                           -- K
(.) :: (b -> c) -> (a -> b) -> (a -> c)        -- B
flip :: (a -> b -> c) -> (b -> a -> c)         -- C
(<*>) :: (a -> b -> c) -> (a -> b) -> (a -> c) -- S


Work with one parameter at a time. Move parameters on the left to lambdas on the right, e.g.

f x y = Z


becomes

f = \x -> \y -> Z


I like to do this one argument at a time rather than all at once, it just looks cleaner.

Then eliminate the lambda you just created according to the following rules. I will use lowercase letters for literal variables, uppercase letters to denote more complex expressions.

1. If you have \x -> x, replace with id
2. If you have \x -> A, where A is any expression in which x does not occur, replace with const A
3. If you have \x -> A x, where x does not occur in A, replace with A. This is known as "eta contraction".
4. If you have \x -> A B, then
1. If x occurs in both A and B, replace with (\x -> A) <*> (\x -> B).
2. If x occurs in just A, replace with flip (\x -> A) B
3. If x occurs in just B, replace with A . (\x -> B),
4. If x does not occur in either A or B, well, there's another rule we should have used already.

And then work inward, eliminating the lambdas that you created.

Sometimes a shortcut with >>= is possible:

1. If you have \x -> A B x, where x does not occur in A, replace with (\x -> B) >>= A.
• in the general case, (\x -> A B x) = join ((\x -> A) <*> (\x -> B)). Jan 30 '18 at 18:35

# Haskell + plumbers

Use the plumbers package for a large collection of infix combinators.

For example,

-- Ungolfed
f (x, y) (z, t) = (x + z, y + t)
-- Golfed (without plumbers)
f(x,y)(z,t)=(x+z,y+t)
-- Golfed (with plumbers)
f=(+)***(+)


Or, let's say we wanted to find the dot product of a list of vectors in the form [(Double, Double)].

-- Ungolfed
g = sum . map (\(x,y) -> x * y)
-- Golfed (without plumbers)
g=sum.map(uncurry(*))
-- Golfed (with plumbers)
g=sum.map((*)$*id)  Plumbers are a great way to pointfree an expression, especially in the middle of a map or a fold. As a quick note, the way to read these operators is as follows. ($**>^)


Every plumber takes two functions as arguments. The first character specifies how to combine the results of the two functions. A * means to return a tuple, and a $ means to pass the result of the second function to the first function. The remaining characters specify what to do with the remaining arguments. < Pass the argument to the left but not the right function > Pass the argument to the right but not the left function & Pass the argument to both functions ^ Ignore the argument completely * The argument is a tuple; split it and pass the parts to the left and right functions  • I like how plumbers calls itself pointless plumbing combinators. Dec 30 '17 at 18:56 # Avoid sorting Haskell doesn't have a built-in sorting in Prelude. It can be accessed with an import: import Data.List sort  This also gives you access to functions like sortOn and sortBy, as well as other functions in Data.List. But, many times you don't need the full power of sorting and can make do without an import. Check if a list is sorted scanl1 max l==l  This requires the list to be nonempty. As a pointfree predicate: (==)=<<scanl1 max  You can likewise check if a list is in descending order with scanr1 max l==l. Sort values lying in a known range If you know the l contains only, say, digits 0 to 9, you can sort it as: [d|d<-[0..9],x<-l,x==d]  This allows for duplicates in l. If you know l doesn't have duplicates, or are fine dropping them, you can do: [d|d<-[0..9],elem d l]  or filter(eleml)[0..9]  These also works if l is a string, enumerating characters as ['\0'..] or [' '..]. The range of characters is very large but bounded. Min and max If you just need the smallest or largest element, minimum or maximum will do. You can also check whether n>=maximum l as all(<=n)l, and similarly for minimum. Sorted index One use of sorting is to find the index of some value n in sorted order within l. You can instead do that by counting smaller elements: sum[1|x<-l,x<n]  If x appears more than once, this gives the index of its first appearance in sorted order. # The function 0^x This maps positive integers to 0 and zero to 1. So, it acts a little bit like !x in C-like languages. It crashes for negative x; in this case you can write 0^x^2, which parses as 0^(x^2). This is not technically specific to Haskell, but Haskell is quite strict about converting between numbers and booleans compared to some other common code golf languages. It's often shorter to use 0^x and stay in Integer-land than to check x==0. Even expressions like 0^(x-42)^2 come in handy sometimes (if x==42 then 1 else 0). Example: if x==0 then 'B' else 'A' last$'B':['A'|x==0]
"AB"!!sum[1|x==0]
"AB"!!(0^x^2)
"AB"!!(0^x)       -- if x is never negative

• If you need to use the arbitrary precision Integer type, it appears that 0^x can also convert x from Integer to Int for use with (!!) Nov 27 '21 at 3:51

# Helper functions

This is (or will) be a list of generic helper functions that occasionally have to be implemented as part of a bigger solution.

• Primality test: p :: Int -> Bool

p n=mod(product[1..n-1]^2)n>0

• Binary to decimal: b :: String -> Int

b=foldl(\a x->2*a+read[x])0

• Decimal to binary: d :: Int -> String

d n=mapM(\_->"01")[1..n]!!n


More to come.

• It might be worth adding two more primality tests: p n=[1|0<-mod n<$>[2..n]]==[1] and p n=all((>0).mod n)[2..n-1]. The former identifies 0 as not prime, the latter is only valid for n>=2. Both can come in handy Jan 5 '18 at 18:03 • Also the ^2 in the primality test is only needed for n==4. Jan 5 '18 at 18:37 • The decimal to binary can be d n=mapM("01"<$d)[1..n]!!n, although that depends on defining it as a function, or having another one-letter Int->something function to put with the <$. Jan 5 '18 at 18:40 • @ØrjanJohansen, some of those tests look similar to Wilson's theorem, but not the same. Where's the square come from? Mar 14 '19 at 20:46 • @dfeuer It's the shortest way to handle the fact that Wilson's product for the number n=4 is 2 (mod n), instead of 0 (mod n) like for all other composites. Mar 14 '19 at 22:36 ## Fixity declarations are your friends As we know it is often cheaper to define an operator instead of a function (see this tip), sometimes it pays off to declare a fixity different from the default (infixl 9). Imagine for example the following which is fairly common (57 bytes): (a:b)!(c:d)=undefined (a:b)!e=undefined e!(a:b)=undefined  In that particular case using a fixity declaration is still 1 byte more expensive (58 bytes): infix 4! a:b!c:d=undefined a:b!e=undefined e!a:b=undefined  As you can see you can use the low fixity to omit several parentheses, if somewhere in your code you have other parentheses that are due to the high default fixity, you can save bytes for these by declaring another fixity. Note: This might seem like an arbitrary example but it is realistic as you can see in this answer. • Jan 10 at 23:15 ### Use pure to build singletons • pure is one byte shorter than (:[]) or Right (thanks, Ørjan Johansen). • pure.f is one byte shorter than Just .f. • pure is shorter than singleton if you need Data.Sequence for some reason. • As Ørjan Johansen points out, this works for the writer monad: pure a=(mempty,a). This may occasionally be useful for something like (Nothing, a). • (,)mempty popped into my mind as another example... not sure how useful. Mar 14 '19 at 23:46 • Oh, and Right too. Mar 15 '19 at 3:43 # Binary op on two-element list You can apply a binary operation to a two-element list like: foldr1(-)[5,3]  to get 5-3, or 2. Note that this operator must output the same type as the input, that is be a -> a -> a. So, foldr1(==)[5,3] doesn't typecheck but foldr1 mod[5,3] does. You can think of this as a list analogue to uncurry(-)(5,3). It may be useful if you take input as a two-element list or one is produced in an intermediate computation, and it would cost extra bytes to match it to [a,b] to extract the values. Using foldl1 gives the same result as foldr1. The best way to flip the order of the operands seems to just be to flip the operator. ## fmap In the spirit of saving characters using infix operators, you could save a couple by replacing something like: map show [1..9]  with: show<$>[1..9]


# Use zip

Often you need to map over a list and apply some function which depends on the index of the argument in the list. while a lot of impure languages who have some sort of map builtin have the index be an optional argument, this is impossible in Haskell. instead, use:

mapWithIndex f xs === f<$>zip[0..]xs === [f i x|(i,x)<-zip[0..]xs] {- inlinable version -} === zipWith f[0..]xs mapWithIndex f === (f<$>).zip[0..]           {- points free version -}


Often this combines well within list comprehensions, where even a builtin mapWithIndex won't help:

    [ ... | ..., (i,x)<-zip[0..]xs, ...]


Other times, you really want to use the nonexistant equivalent maximumOn of sortOn, but the import is too many bytes, or using maximumBy is too many bytes too. instead, use*:

sortOn f xs === snd$sort$(f>>=(,))<$>xs === snd$sort[(f x,x)|x<-xs]   {- inlinable version -}

# Pattern match inside list comprehensions

Suppose you have code that looks like (imports for purpose of demonstration)

import Data.List (lookup)
import Data.Maybe (catMaybes)

ys = [(1,"a"), (3, "b"), (5, "c"), (7, "d")]
catMaybes [lookup x ys | x <- [1..10]]


You can change this to

[y | x <- [1..10], Just y <-[lookup x ys]]


I found it particularly helpful when I was pattern matching in a function definition

f (x:xs) = [foo x x'| x' <-[1..10]]
f [] = []


when I could instead put the pattern matching logic inside the list comprehension.

f lst = [foo x x' | x:xs<-[lst], x'<-[1..10]]


This works because incomplete pattern matches are desuarged to mfail instead of error in do notation, so for things like the list monad, we get the empty list. It can be used with do notation for other monads, too, although pure is probably the shortest alternative to [].

f :: [Int] -> Maybe String
f lst = do
1:xs <- pure lst
pure "one"

• Some notes: (1) lookup itself can be replaced by pattern matching if you know there cannot be more than one match. (2) You don't need parentheses around patterns before <-. (3) You can shorten [foo x x' | (x:xs)<-[lst], x'<-[1..10]] further to [foo x|x:xs<-[lst]]<*>[1..10]. Jun 29 '19 at 1:57
• @ØrjanJohansen nice catch on the parentheses, and yeah I’m sure there are other tricks, these were contrived examples to demonstrate the utility.
– cole
Jun 29 '19 at 2:23