Hot answers tagged

86

Haskell, 26 bytes (++"[]").((++":").show=<<) Try it online! Explanation: In non-pointfree notation and using concatMap instead of =<<, this becomes f s = concatMap(\c-> show c ++ ":")s ++ "[]" Given a string s, we map each char c to a string "'c':" using the show function which returns a string representation of most Haskell types. ...


45

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 ...


44

Haskell, 33 28 26 bytes foldr((.(':':)).shows)"[]" Try it online! fold the given pointfree function from the right into the input string starting with []. The function is: show char as a Haskell char, i.e. surrounded with ' and concatenate with the result so far after putting a : in front of it. Edit: @Ørjan Johansen saved two bytes. Thanks!


29

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)


29

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 ...


28

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 ...


24

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&...


24

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!


24

MagicHash, 30 bytes x=1 y#a=2 x#a=1 main=print$x#x -XMagicHash outputs 1, -XNoMagicHash outputs 2 MagicHash allows variable names to terminate in a #. Therefore with the extension, this defines two functions y# and x# which each take a value and return a constant 2, or 1. x#x will return 1 (because it is x# applied to 1) Without the extension, this ...


23

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


22

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","...


19

Python 3, 32 bytes lambda s:"%r:"*len(s)%(*s,)+"[]" Try it online!


19

CPP, 33 20 bytes main=print$0-- \ +1 Prints 0 with -XCPP and 1 with -XNoCPP. With -XCPP, a slash \ before a newline removes the newline, thus the code becomes main=print$0-- +1 and only 0 is printed as the +1 is now part of the comment. Without the flag the comment is ignored and the second line is parsed as a part of the previous line because it is ...


18

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 ...


17

JavaScript ES6, 42 40 31 bytes s=>s.replace(/./g,"'$&':")+"[]" Replaces each char with '<char>':, then adds [] to the end Try it online!


17

Haskell, 169 148 bytes init.tail.fst.([]%) p:k="(," l%('(':r)|(y,x:s)<-[]%r,m<-y:l=last$m%(p:s):[(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)|x<','] l%r=lex r!!0 Try it online! Takes the tuple as a string. init.tail.fst.([]%) is the anonymous main function. Bind it to e.g. f and use like f "(3,(14,1),4,7)", which yields "(,...


16

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. ...


16

Common Lisp, 50 42 bytes (format t"~{'~a':~}[]"(coerce(read)'list)) Try it online! Reduced thanks to the comment of @coredump, by using read instead of defining a function.


15

Know your monadic functions 1)simulate monadic functions using mapM. 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 ...


15

Arguments can be shorter than definitions I just got outgolfed in a very curious way by henkma. If an auxiliary function f in your answer uses an operator that isn’t used elsewhere in your answer, and f is called once, make the operator an argument of f. This: (!)=take f a=5!a++3!a reverse.f Is two bytes longer than this: f(!)a=5!a++3!a reverse.f take


14

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


14

BinaryLiterals, 57 bytes b1=1 instance Show(a->b)where;show _="" main=print$(+)0b1 -XBinaryLiterals prints a single newline. -XNoBinaryLiterals prints a 1. I am sure there is a better way to do this. If you find one, please post it.


14

NumDecimals, 14 bytes main=print 1e1 -XNumDecimals prints 10. -XNoNumDecimals prints 10.0.


12

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. If e is even moderately complex, you will need ...


12

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


12

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


12

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 ...


12

MonomorphismRestriction + 7 others, 107 bytes This uses TH which requires the flag -XTemplateHaskell at all times. File T.hs, 81 + 4 bytes module T where import Language.Haskell.TH p=(+) t=reify(mkName"p")>>=stringE.show Main, 22 bytes import T main=print $t Compiling with the flag MonomorphismRestriction forces the type of p to Integer -> ...


11

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 ...


11

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: (x`v`) Although it is the same as just v x. Another example is writing (x+1)`div`y as opposed to div(x+1)y. I see it happen around div and elem more often because these functions are ...


Only top voted, non community-wiki answers of a minimum length are eligible