# 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? – Animesh 'the CODER' 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. – unclemeat 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. – MasterMastic Jun 1 '14 at 12:10
• Special request, String compression. – J Atkin 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 – flawr 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!

# Use GHC 8.4.1 (or later)

With the Semigroup Monoid Proposal and the release of GHC 8.4.1, Semigroup has been moved to the Prelude. This gives us:

(<>) :: Semigroup a => a -> a -> a


Now these might seem useless at first glance, but looking closer we notice that Monoid a => (x -> a) is an instance of Monoid1, in which case we have the implementation:

(f <> g) xs = f xs <> g xs


This can be quite useful with for example lists, knowing that (<>) is the same as (++) for lists. So we have for example:

(init <> reverse) [1,2,3] ≡ init [1,2,3] <> reverse [1,2,3]
≡ [1,2] <> [3,2,1]
≡ [1,2] ++ [3,2,1]
≡ [1,2,3,2,1]


However, this is not the only useful case: Knowing that [x] -> [x] is an instance of Monoid, we also have a -> [x] -> [x] an instance of Monoid (you can iterate this as many times as you want):

(drop <> take) 2 [1,2,3,4,5] ≡ (drop 2 <> take 2) [1,2,3,4,5]
≡ drop 2 [1,2,3,4,5] <> take 2 [1,2,3,4,5]
≡ [3,4,5] <> [1,2]
≡ [3,4,5,1,2]


1: Note that Monoid a $$\\implies\$$ Semigroup a.

## Overview what we gained so far

Using this trick we have these (not exhaustive) helpers, note that we can chain them:

duplicate    = id <> id
triple²      = id <> id <> id
palindromize = init <> reverse
rotateLeft   = drop <> take
removeElementAt = take <> drop . succ
removeNElementsAt n = take <> drop . (+n)


2: This could also be ([1..3]>>) for the same bytecount be shorter (see comment by Ørjan Johansen).

## Where are the $$\(\mathbb{Z},\texttt{+})\$$ and $$\(\mathbb{Z},\texttt{*})\$$ monoids?

If we want to use the $$\(\mathbb{Z},\texttt{+})\$$ monoid, we need to tell GHC that. It can not decide for us which one it should use, therefore there are two newtypes which allow this - Sum and Product.

Given that the consensus is to allow implicitly typed functions, we are probably allowed to do so if the challenge does not talk about a specific implementation for integers. Using this we can for example write $$\n\$$th oblong number as

id<>(+1)


which is shorter than f n=n*(n-1) or even (*)=<<succ/(*)<*>succ.

3: Note that we need to use (+1) and cannot use succ since GHC can't know that there is an instance of Enum.

## Other noteworthy related tricks

Instances that might be useful not covered above:

()
Ordering
(Monoid a, Monoid b) => Monoid (a,b)  -- (also 3-,4- and 5-tuples)
Monoid a => Monoid (IO a)
Ord k => Monoid (Map k v)             -- from Data.Map


It might be worth noting that there is mconcat too:

mconcat [f1,f2,…,fN] ≡ f1 <> f2 <> … <> fN


This will probably not be useful often, for it needs at least $$\3-11\$$ functions (depending on the need of parentheses, see comments), but it might be in case you have some list Monoid a => [a] already.

Furthermore mempty can be useful since it is shorter than Nothing or even pure Nothing, ([],[]) etc.

Another useful instance is Monoid a => Monoid (IO a) which has successfully been used for the currently shortest quine as

(putStr <> print) "foo" ≡ putStr "foo" <> print "foo"
≡ do x <- putStr "foo"
y <- print "foo"
pure $x <> y ≡ do putStr "foo" print "foo" pure () ≡ putStr "foo" >> print "foo"  • ("123">>) is shorter. – Ørjan Johansen Dec 19 '18 at 16:23 • @ØrjanJohansen: Ah damn, it was meant for educational purposes :P (showing that you can join multiple functions, not only two) – ბიმო Dec 19 '18 at 16:25 • By my count 8−11 functions should be 4−11. (Best case if all functions need parentheses with <>.) – Ørjan Johansen Dec 19 '18 at 16:38 • Oh, I thought of parentheses around each individual function, but I did not consider parentheses around the whole. In that case it can beat it with 3: mconcat[f1,f2,f3] is a byte shorter than ((f1)<>(f2)<>(f3)). – Ørjan Johansen Dec 19 '18 at 17:37 • @ØrjanJohansen: If someone actually needs all these parens, maybe they should switch to LISP ^^ Seriously though, a lot of times the outer parentheses are needed, unfortunately. And it's a fair point with the inner parentheses, with the list one does not need to shy away from using ($). – ბიმო Dec 19 '18 at 17:45

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.

{-# LANGUAGE CPP #-}
f=\


Example here.

• Golfier: Add a -cpp compiler flag. – Laikoni Oct 31 '17 at 21:22

# 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. – Bubbler Jan 18 at 7:20

# 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. – Ørjan Johansen Jan 11 '18 at 19:26 # 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. – Zgarb 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. – Laikoni Jan 18 '17 at 15:18
• @Zgarb TIO's ghc was updated to 8.0.2 thanks to Dennis. – Laikoni Jan 22 '17 at 20:06
• TIOv2 Alpha was replaced with a fork of TIO Nexus, so GHC8.0.2 should be supported. – CalculatorFeline Jun 1 '17 at 15:38

## 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 . – Laikoni Apr 24 '17 at 20:44 # 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] – Julian Wolf Jul 6 '17 at 23:15 # 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. – Dennis Dec 30 '17 at 18:56

# 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. – Zgarb 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. – Renzeee Jan 11 '17 at 8:15
• The same goes for chr and toEnum, however the type of toEnum needs to be forced from context. – Laikoni Jan 13 '17 at 16:14

# 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)). – Will Ness Jan 30 '18 at 18:35

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)

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

## 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]  # 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 – H.PWiz Jan 5 '18 at 18:03
• Also the ^2 in the primality test is only needed for n==4. – Ørjan Johansen 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 <$. – Ørjan Johansen 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? – dfeuer Mar 14 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. – Ørjan Johansen Mar 14 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.

# 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 -}
sortOn f    === snd.sort.(f>>=(,)<$>) {- points free version -}  Note that sometimes you will need both the best x and its f x, in which case you can get rid of three bytes and have it computed for you for free! many other uses for this combination are possible too. • I don't think f<$>zip[0..]xs works as [f i x|(i,x)<-zip[0..]xs]. You'd need uncurry f<$>zip[0..]xs, since f is being given tuples of (i,x). It would work to do zipWith f[0..]xs, – xnor Mar 27 '16 at 23:16 • @xnor as the code golfer, you can modify your f whatever way fits best. We're not writing library functions here. – proud haskeller Mar 27 '16 at 23:19 • @xnor Oh, that's a way I haven't thought of! I'll add it. – proud haskeller Mar 27 '16 at 23:20 • Oh, you're saying that f is the outer function that you're defining in the code golf challenge, and so you can choose whether it's curried or takes a tuple? That definitely works for that case, but it wasn't clear from reading it that it wasn't meant to apply to functions you define as as subpart of your golf. – xnor Mar 27 '16 at 23:22 • @xnor even if f isn't a function you defined yourself, then the fact that both options are possible is useful, because using curry or uncurry will probably be longer than just switching to one of the other options presented here. – proud haskeller Mar 27 '16 at 23:26 ## Use empty let instead of otherwise/True x&y|x=y|let=x -- Boolean and  While it is no shorter than using 1>0 and usually it makes more sense to use the guard to bind a variable it can be useful when there are source restrictions or the prelude is not in scope. This works because let statements in guards behave as always true and an empty let is valid. Empty let also works in list comprehensions, but I believe it completely useless for golfing in that position as it can be omitted. Use pure instead of const. I saw this in someone else's answer, but I don't know where. Of course, it's often better to use a lambda if it's applied. There's an occasional one byte shorter trick than the lambda \_->x: Use x<$f where f is any one-letter function that just happens to have the same input type as what you want. Note that this never evaluates f itself at all.

### 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. – Ørjan Johansen Mar 14 at 23:46
• Oh, and Right too. – Ørjan Johansen Mar 15 at 3:43

# 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]. – Ørjan Johansen Jun 29 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 at 2:23