# 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

# Define infix operators instead of binary functions

This saves usually one or two spaces per definition or call.

0!(y:_)=y
x!(y:z)=(x-1)!z

vs.

f 0(y:_)=y
f x(y:z)=f(x-1)z

The available symbols for 1-byte operators are !, #, %, &, and ?. All other ASCII punctuation is either already defined as an operator by the Prelude (such as $) or has a special meaning in Haskell's syntax (such as @). If you need more than five operators, you could use combinations of the above, such as !#, or certain Unicode punctuation characters, such as these (all 2 bytes in UTF-8): ¡ ¢ £ ¤ ¥ ¦ § ¨ © ¬ ® ¯ ° ± ´ ¶ · ¸ ¿ × ÷ • Note: this can also be used for functions with three or more arguments. (x!y)z=x+y*z and (x#y)z u=x*z+y*u both work as expected. – Zgarb Oct 15 '15 at 13:35 • This can also be used for function arguments, e.g. \f g(!)x y->f g!x y instead of \f g j x y->j(f g)(x y) – Esolanging Fruit Nov 12 '17 at 3:13 • Sometimes it's beneficial to change unary functions to binary operators if you'd otherwise have to use parentheses - g x=…;g(f x) is longer than _?x=…;0!f x – Angs May 12 '18 at 17:11 Use pointless (or -free) notation where appropriate Often a function with one or two parameters can be written point free. So a lookup for a list of tuples whose elements are swapped is naïvely written as: revlookup :: Eq b => b -> [(a, b)] -> Maybe a revlookup e l=lookup e(map swap l) (the type is there just to help you understand what it's doing.) for our purposes this is much better: revlookup=(.map swap).lookup Use guards not conditionals: f a=if a>0 then 3 else 7 g a|a>0=3|True=7 Use semicolons not indents f a=do this that g a=do this;that Use boolean expressions for boolean functions f a=if zzz then True else f yyy g a=zzz||f yyy (SO is being a pain about letting me post these separately) • also, use multiple guards instead of && when inside a list comprehension. – John Dvorak Mar 21 '14 at 14:11 • Good one Jan - you should make that into an answer, I'll vote for it – bazzargh Mar 21 '14 at 14:31 • The first example can be further shortened by True => 1>0 – John Dvorak Feb 22 '16 at 9:10 • in the first example, I assume you mean f a=if a>0 then 3 else 7 – Cyoce Apr 2 '16 at 1:24 • Guard even works if there's no argument in it. – Akangka Oct 23 '16 at 12:18 Use 1<2 instead of True and 1>2 instead of False. g x|x<10=10|True=x f x|x<10=10|1<2=x • This isn't really specific to Haskell: it's applicable to just about every language which has a Boolean type as opposed to truthy and falsy values of other types. – Peter Taylor Apr 7 '14 at 11:14 • Can anyone explain this? – MasterMastic Jun 1 '14 at 12:12 • this isn't a good example, i would just golf this as f=max 10. – proud haskeller Aug 17 '14 at 14:51 • @MasterMastic this is just writing if(true) in other languages. in the prelude, otherwise is actually the boolean value True. – proud haskeller Aug 17 '14 at 15:08 • @PeterTaylor I think this is still valuable for new haskellians (like me) as I first learned to use otherwise. – flawr Jun 11 '16 at 9:12 Use words instead of a long list of strings. This isn't really specific to Haskell, other languages have similar tricks too. ["foo","bar"] words"foo bar" -- 1 byte longer ["foo","bar","baz"] words"foo bar baz" -- 1 byte shorter ["foo","bar","baz","qux"] words"foo bar baz qux" -- 3 bytes shorter Don't use backticks too often. Backticks are a cool tool for making sections of prefix functions, but can sometimes be misused. Once I saw someone write this subexpression: (xv) Although it is the same as just v x. Another example is writing (x+1)divy as opposed to div(x+1)y. I see it happen around div and elem more often because these functions are usually used as infix in regular code. • Don't you mean making sections of prefix functions? – Cyoce Apr 2 '16 at 3:15 • @Cyoce Yes, of course – proud haskeller Apr 2 '16 at 6:28 # interact :: (String → String) → IO () People often forget that this function exists - it grabs all of stdin and applies it to a (pure) function. I often see main-code along the lines of main=getContents>>=print.foo while main=interact$show.foo

is quite a bit shorter. It is in the Prelude so no need for imports!

# Lambda parsing rules

A lambda-expression doesn't actually need parentheses around it - it just rather greedily grabs everything so the whole thing still parses, e.g. until

• a closing paren - (foo$\x -> succ x) • an in - let a = \x -> succ x in a 4 • the end of the line - main = getContents>>= \x -> head$ words x
• etc..

is encountered, and there are some weird edge-cases where this can save you a byte or two. I believe \ can also be used to define operators, so when exploiting this you will need a space when writing a lambda directly after an operator (like in the third example).

Here is an example of where using a lambda was the shortest thing I could figure out. The code basically looks like:

a%f=...
f t=sortBy(% \c->...)['A'..'Z']

# Use the cons operator (:)

when concatenating lists, if the first is of length 1 then use : instead.

a++" "++b
a++' ':b  -- one character shorter

[3]++l
3:l    -- three characters shorter
• Worth noting that it's right associative, so you can keep using it for any number of single items at the beginning of the list, e.g. 1:2:3:x rather than [1,2,3]++x. – Jules Jul 22 '16 at 19:47

1)

a lot of times code will have sequence(map f xs), but it can be replaced with mapM f xs. even when just using sequence alone it is longer then mapM id.

2)
combine functions using (>>=) (or (=<<))

the function monad version of (>>=) is defined as so:

(f >>= g) x = g (f x) x

it can be useful for creating functions which can't be expressed as a pipeline. for example, \x->x==nub x is longer than nub>>=(==), and \t->zip(tail t)t is longer than tail>>=zip.

• +1 -- I hadn't even realised that there was a monad instance for functions. that could be very handy :) – Jules Jul 22 '16 at 19:42
• Side note: Though it's part of Applicative and not Monad there's the implementation for pure as well which is shorter than const and actually helped me before. – ბიმო Jan 5 '18 at 19:02

## Replace let by lambda

This can usually shorten a lone auxiliary definition that can't be bound with a guard or defined globally for some reason. For example, replace

let c=foo a in bar

by the 3 bytes shorter

(\c->bar)$foo a For multiple auxiliary definitions, the gain is probably smaller, depending on the number of definitions. let{c=foo a;n=bar a}in baz (\c n->baz)(foo a)$bar a

let{c=foo a;n=bar a;m=baz a}in qux
(\c n m->qux)(foo a)(bar a)$baz a let{c=foo a;n=bar a;m=baz a;l=qux a}in quux (\c n m l->quux)(foo a)(bar a)(baz a)$qux a

If some of the definitions refer to the others, it is even harder to save bytes this way:

let{c=foo a;n=bar c}in baz
(\c->(\n->baz)$bar c)$foo a

The main caveat with this is that let allows you to define polymorphic variables, but lambdas do not, as noted by @ChristianSievers. For example,

let f=length in(f["True"],f[True])

results in (1,1), but

(\f->(f["True"],f[True]))length

gives a type error.

• It rarely matters, but "semantically equivalent" promises a bit too much. We have polymorpic let, so we can do let f=id in (f 0,f True). If we try to rewrite this with lambda it doesn't type check. – Christian Sievers Jan 17 '17 at 21:09
• @ChristianSievers That's true, thanks for the note. I edited it in. – Zgarb Jan 18 '17 at 8:13

## 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] # Know your Prelude Fire up GHCi and scroll through the Prelude documentation. Whenever you cross a function that has a short name, it can pay off to look for some cases where it might be useful. For example, suppose you wish to transform a string s = "abc\ndef\nghi" into one that's space-separated, "abc def ghi". The obvious way is: unwords$lines s

But you can do better if you abuse max, and the fact that \n < space < printable ASCII:

max ' '<$>s Another example is lex :: String -> [(String, String)], which does something quite mysterious: Prelude> lex " some string of Haskell tokens 123 " [("some"," string of Haskell tokens 123 ")] Try fst=<<lex s to get the first token from a string, skipping whitespace. Here is a clever solution by henkma that uses lex.show on Rational values. # Use the list monad A quick review: xs >> ys = concat$ replicate (length xs) ys
xs >>= f        =  concatMap f xs
mapM id[a,b,c]  =  cartesian product of lists: a × b × c
mapM f[a,b,c]   =  cartesian product of lists: f a × f b × f c

Examples:

• ### Repeating a list twice

Prelude> "aa">>[1..5]
[1,2,3,4,5,1,2,3,4,5]

• ### Shorter concatMap

Prelude> reverse=<<["Abc","Defgh","Ijkl"]
"cbAhgfeDlkjI"

• ### Shorter concat + list comprehension

Prelude> do x<-[1..5];[1..x]
[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5]

• ### Cartesian product

Prelude> mapM id["Hh","io",".!"]
["Hi.","Hi!","Ho.","Ho!","hi.","hi!","ho.","ho!"]

• ### List of coordinates on a lattice

Prelude> mapM(\x->[0..x])[3,2]
[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]]

• Annother use I found useful is [0..b]>>[a] instead of replicate a b. – Sriotchilism O'Zaic Jun 24 '17 at 3:04
• @WheatWizard a<$[1..b] is even shorter, for replicate. – Lynn Jul 31 '17 at 9:39 • Using =<< forces you to import Control.Monad. If you don't need that for some other reason, swapping the arguments and using >>= seems more concise. – dfeuer Dec 5 '17 at 18:51 • OTOH, if you need Data.Traversable anyway, the Cartesian product example can be shortened to for["Hh","io",".!"]id. – dfeuer Dec 5 '17 at 18:53 • (=<<) is in Prelude, actually! I've used it a lot. – Lynn Dec 5 '17 at 20:08 # Use GHC 7.10 The first version of GHC that contained this stuff was released on March 27, 2015. It's the latest version, and Prelude got some new additions that are useful for golfing: ## The (<$>) and (<*>) operators

These useful operators from Data.Applicative made it in! <$> is just fmap, so you can replace map f x and fmap f x with f<$>x everywhere and win back bytes. Also, <*> is useful in the Applicative instance for lists:

Prelude> (,)<$>[1..2]<*>"abcd" [(1,'a'),(1,'b'),(1,'c'),(1,'d'),(2,'a'),(2,'b'),(2,'c'),(2,'d')] ## The (<$) operator

x<$a is equivalent to fmap (const x) a; i.e. replace every element in a container by x. This is often a nice alternative to replicate: 4<$[1..n] is shorter than replicate n 4.

## The Foldable/Traversable Proposal

The following functions got lifted from working on lists [a] to general Foldable types t a:

fold*, null, length, elem, maximum, minimum, sum, product
and, or, any, all, concat, concatMap

This means they now also work on Maybe a, where they behave just like "lists with at most one element". For example, null Nothing == True, or sum (Just 3) == 3. Similarly, length returns 0 for Nothing and 1 for Just values. Instead of writing x==Just y you can write elem y x.

You can also apply them on tuples, which works as if you'd called \(a, b) -> [b] first. It's almost completely useless, but or :: (a, Bool) -> Bool is one character shorter than snd, and elem b is shorter than (==b).snd.

## The Monoid functions mempty and mappend

Not often a life-saver, but if you can infer the type, mempty is one byte shorter than Nothing, so there's that.

• +1 It's great to hear about '<$> and <*> making it into Prelude! That should be usefull even when It's not code golf (applicative is such a long word). – ankh-morpork Jul 10 '15 at 22:20 • Warning about flat replacement: if your language version is newer than the challenge, your solution is inegligible for winning. If you want to update your existing answers or answer, don't overwrite your existing solution. Write an appendix. – John Dvorak Jul 11 '15 at 5:32 • Funny there is [1..2] in there. that's just [1,2] – proud haskeller Aug 26 '15 at 8:08 • In the same version we also got <* from Applicative, which for lists is xs <* ys == concatMap (replicate (length ys)) xs. This is different from xs >> ys or xs *> ys which is concat (replicate (length ys)) xs. pure which is a shorter return came at this point too. – Angs Nov 7 '16 at 9:04 • You can now use <> instead of mappend, it's now (with GHC 8.4.1) part of the Prelude. – ბიმო Mar 10 '18 at 15:50 # Use list comprehensions (in clever ways) Everyone knows they're useful syntax, often shorter than map + a lambda: Prelude> [[1..x]>>show x|x<-[1..9]] ["1","22","333","4444","55555","666666","7777777","88888888","999999999"] Or filter (and optionally a map at the same time): Prelude> [show x|x<-[1..60],mod 60x<1] ["1","2","3","4","5","6","10","12","15","20","30","60"] But there are some weirder uses that come in handy now and then. For one, a list comprehension doesn't need to contain any <- arrows at all: Prelude> [1|False] [] Prelude> [1|True] [1] Which means instead of if p then[x]else[], you can write [x|p]. Also, to count the number of elements of a list satisfying a condition, intuitively you would write: length$filter p x

But this is shorter:

sum[1|y<-x,p y]
• I actually used all of these before, but I didn't think to put them here. – proud haskeller Aug 26 '15 at 8:10

# Use pattern guards

They're shorter than a let or a lambda that deconstructs the arguments of a function you're defining. This helps when you need something like fromJust from Data.Maybe:

f x=let Just c=… in c

is longer than

f x=(\(Just c)->c)$… is longer than m(Just c)=c;f x=m$…

is longer than

f x|Just c<-…=c

In fact, they’re shorter even when binding a plain old value instead of deconstructing: see xnor’s tip.

• Well, the lambda one doesn't need the dollar sign, and it seems this change makes the lengths of this and the next snippet the same – proud haskeller Aug 26 '15 at 8:13
• I'm assuming e isn't actually one token but a longer expression that needs $before it, which is usually the case. – Lynn Aug 26 '15 at 14:52 ## Try rearranging function definitions and/or arguments You can sometimes save a couple of bytes by changing the order of pattern-matching cases in a function definition. These savings are cheap, but easy to overlook. As an example, consider the following earlier version of (a part of) this answer: (g?x)[]=x (g?x)(a:b)=g(g?x$b)a

This is a recursive definition of ?, with the base case being the empty list. Since [] is not a useful value, we should swap the definitions and replace it with the wildcard _ or a dummy argument y, saving a byte:

(g?x)(a:b)=g(g?x$b)a (g?x)y=x From the same answer, consider this definition: f#[]=[] f#(a:b)=f a:f#b The empty list occurs in the return value, so we can save two bytes by swapping the cases: f#(a:b)=f a:f#b f#x=x Also, the order of function arguments can sometimes make a difference by allowing you to remove unnecessary whitespace. Consider an earlier version of this answer: h p q a|a>z=0:h p(q+2)(a-1%q)|1<2=1:h(p+2)q(a+1%p) There's an annoying piece of whitespace between h and p in the first branch. We can get rid of it by defining h a p q instead of h p q a: h a p q|a>z=0:h(a-1%q)p(q+2)|1<2=1:h(a+1%p)(p+2)q # 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 -} (This also gives us 1-based indexing for free!) 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

## Bind using guards

When defining a named function, you can bind an expression to a variable in a guard. For example,

f s|w<-words s=...

does the same as

f s=let w=words s in ...
f s=(\w->...)$words s Use this to save on repeated expressions. When the expression is used twice, it breaks even at length 6, though spacing and precedence issues can change that. (In the example, if the original variable s is not used, it's shorter to do g w=... f=g.words but that's not true for binding more complex expressions.) • Isn’t this sort of a duplicate/special case of this answer? – Lynn Aug 9 '16 at 10:27 • @Lynn Looking back, it's a special case, but when I read that answer, the Just example made me think it's for pattern-matching to extract from a container, rather than to store on an expression. – xnor Aug 10 '16 at 10:14 ## Match a constant value A list comprehension can pattern match on a constant. [0|0<-l] This extracts the 0's of a list l, i.e. makes a list of as many 0's as are in l. [1|[]<-f<$>l]

This makes a list of as many 1's as there are elements of l that f takes to the empty list (using <$> as infix map). Apply sum to count these elements. Compare: [1|[]<-f<$>l]
[1|x<-l,f x==[]]

[x|(0,x)<-l]

A constant can be used as part of a pattern match. This extracts the second entries of all tuples whose first entry is 0.

Note that all of these require an actual constant literal, not a the value of a variable. For example, let x=1 in [1|x<-[1,2,3]] will output [1,1,1], not [1], because the outer x binding is overwritten.

# 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])]

## Don't waste the "otherwise" guard

A final guard that's a catch-all True (shorter as 1>0) can be used to bind a variable. Compare:

... |1>0=1/(x+y)
... |z<-x+y=1/z

... |1>0=sum l-sum m
... |s<-sum=s l-s m

Since the guard is mandatory and is otherwise wasted, little is needed to make this worth it. It's enough to save a pair of parens or bind a length-3 expression that's used twice. Sometimes you can negate guards to make the final case be the expression that best uses a binding.

## Use , instead of && in guards

Multiple conditions in a guard that all have to hold can be combined with , instead of &&.

f a b | a/=5 && b/=7 = ...
f a b | a/=5 ,  b/=7 = ...
• It doesn't have to be conditions either, you can do things like this: f xs m | [x] <- xs, Just y <- m, x > 3 = y – BlackCap Dec 16 '16 at 18:22

## Get suffixes

Use scanr(:)[] to get the suffixes of a list:

λ scanr(:)[] "abc"
["abc","bc","c",""]

This is much shorter than tails after import Data.List. You can do prefixes with scanr(\_->init)=<<id (found by Ørjan Johansen).

λ  scanr(\_->init)=<<id $"abc" ["","a","ab","abc"] This saves a byte over scanl(\s c->s++[c])[] • Perhaps scanl(flip(:))[] "abc" = ["","a","ba","cba"] is also worth mentioning – sometimes the prefixes being backwards doesn't matter. – Lynn May 28 '18 at 10:50 • Ørjan Johansen found a one-byte shorter alternative for prefixes: scanr(\_->init)=<<id – Laikoni Dec 8 '18 at 17:36 # Lambdabot Haskell 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! ## Shorter conditional last$x:[y|b]

is equivalent to

if b then y else x

Here's how it works:

[y|b]   x:[y|b]   last$x:[y|b] if... +-------------------------------- b == False | [] [x] x b == True | [y] [x,y] y • Should it be if b then y else x? – Akangka Oct 23 '16 at 11:52 • @ChristianIrwan Good catch, yes. – xnor Oct 23 '16 at 22:09 • Wouldnt using bool be shorter as you don't need a list comprehension – Potato44 Jun 20 '17 at 20:17 • @Potato44 That's in Data.Bool, which costs bytes to import. – xnor Jun 20 '17 at 20:39 ## 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

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

## Working with the minus sign

The minus sign - is an annoying exception to many syntax rules. This tip lists some short ways of expressing negation and subtraction in Haskell. Please let me know if I've missed something.

### Negation

• To negate an expression e, just do -e. For example, -length[1,2] gives -2.