title: Tips for golfing in Haskell

text:
# Question
Title: 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.

# Answer
# 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):

```
¡ ¢ £ ¤ ¥ ¦ § ¨ © ¬ ® ¯ ° ± ´ ¶ · ¸ ¿ × ÷

```
> 51 votes

# Answer
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

```
> 34 votes

# Answer
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)
> 34 votes

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

```
> 32 votes

# Answer
# 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.
> 27 votes

# Answer
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

```
> 26 votes

# Answer
# `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!
> 25 votes

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

```
> 25 votes

# Answer
## 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.
> 22 votes

# Answer
# 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.
> 21 votes

# Answer
# 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

```
> 19 votes

# Answer
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

```
> 17 votes

# Answer
## 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

```
> 17 votes

# Answer
# 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 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`.
> 16 votes

# Answer
# Shorter conditionals when one outcome is the empty list

When you need a conditional which returns the list `A` or the empty list `[]` depending on some condition `C`, then there exist some shorter alternatives to the usual conditional constructs:

```
if(C)then(A)else[] -- the normal conditional
last$[]:[A|C]      -- the golfy all-round-conditional
concat[A|C]        -- shorter and works when surrounded by infix operator
id=<<[A|C]         -- even shorter but might conflict with other infix operators
[x|C,x<-A]         -- same length and no-conflict-guarantee™
[0|C]>>A           -- shortest way, but needs surrounding parenthesis more often than not
do[0|C];A          -- longer but works in some places where the above would need parents

```

Examples: ,
> 16 votes

# Answer
## 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.
> 15 votes

# Answer
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 usually used as infix in regular code.
> 14 votes

# Answer
# 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

```
> 14 votes

# Answer
# 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.
> 14 votes

# Answer
# 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 `Monoid`1, 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 `newtype`s 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`.

Try it online!3

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"

```
> 14 votes

# Answer
# Shorter syntax for local declarations

Sometimes you need to define a local function or operator, but it costs lots of bytes to write `where` or `let…in` or to lift it to top-level by adding extra arguments.

```
g~(a:b)=2!g b where k!l=k:take(a-1)l++(k+1)!drop(a-1)l
g~(a:b)=let k!l=k:take(a-1)l++(k+1)!drop(a-1)l in 2!g b
g~(a:b)=2!g b$a;(k!l)a=k:take(a-1)l++((k+1)!drop(a-1)l)a

```

Fortunately, Haskell has a confusing and seldom-used but reasonably terse syntax for local declarations:

```
fun1 pattern1 | let fun2 pattern2 = expr2 = expr1

```

In this case:

```
g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b

```

You can use this syntax with multi-statement declarations or multiple declarations, and it even nests:

```
fun1 pattern1 | let fun2 pattern2 = expr2; fun2 pattern2' = expr2' = expr1
fun1 pattern1 | let fun2 pattern2 = expr2; fun3 pattern3 = expr3 = expr1
fun1 pattern1 | let fun2 pattern2 | let fun3 pattern3 = expr3 = expr2 = expr1

```

It also works for binding variables or other patterns, though pattern guards tend to be shorter for that unless you’re also binding functions.
> 13 votes

# Answer
# 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']

```
> 12 votes

# Answer
## 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

```
> 12 votes

# Answer
## 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 parentheses around `e`, but you can usually save a byte by moving them around: `-length(take 3 x)` is shorter than `-(length$take 3 x)`.
* If `e` is preceded by `=` or an infix operator of fixity less than 6, you need a space: `f= -2` defines `f` and `k< -2` tests if `k` is less than `-2`. If the fixity is 6 or greater, you need parens: `2^^(-2)` gives `0.25`. You can usually rearrange stuff to get rid of these: for example, do `-k>2` instead of `k< -2`.
* Similarly, if `!` is an operator, then `-a!b` is parsed as `(-a)!b` if the fixity of `!` is at most 6 (so `-1<1` gives `True`), and `-(a!b)` otherwise (so `-[1,2]!!0` gives `-1`). The default fixity of user-defined operators and backticked functions is 9, so they follow the second rule.
* To turn negation into a function (to use with `map` etc), use the section `(0-)`.

### Subtraction

* To get a function that subtracts `k`, use the section `(-k+)`, which adds `-k`. `k` can even be a pretty complex expression: `(-2*length x+)` works as expected.
* To subtract 1, use `pred` instead, unless it would require a space on both sides. This is rare and usually happens with `until` or a user-defined function, since `map pred x` can be replaced by `pred<$>x` and `iterate pred x` by `[x,x-1..]`. And if you have `f pred x` somewhere, you should probably define `f` as an infix function anyway. See this tip.
> 12 votes

# Answer
## 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 = ...

```
> 11 votes

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

```
> 11 votes

# Answer
# Avoid `repeat n`

```
-- 8 bytes, whitespace might be needed before and after
repeat n

-- 8 bytes, whitespace might be needed before
cycle[n]

-- 7 bytes, whitespace might be needed before and after, can be reused,
-- needs an assignment, n needs to be global
l=n:l;l

-- 7 bytes, never needs whitespace, n needs to derive from Enum,
-- n has to be short enough to be repeated twice
[n,n..]

```

Either of those four expressions will produce an infinite list of `n`'s.

It's a very specific tip but it can save up to **3** bytes!
> 11 votes

# Answer
## 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.)
> 10 votes

# Answer
# Shorter `transpose`

To use the `transpose` function `Data.List` has to be imported. If this is the only function needing the import, one can save a byte using the following `foldr` definition of `transpose`:

```
import Data.List;transpose
e=[]:e;foldr(zipWith(:))e

```

Note that the behaviour is only identical for a list of lists with the same length.

I successfully used this here.
> 10 votes

# Answer
# 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.
> 10 votes

# Answer
## 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.
> 9 votes

# Answer
# 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!
> 9 votes

# Answer
# 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`.
* **pointfree.pages.dev** is an alternative site for pointfree.io (which is down at the time of editing).
* **Hoogle**

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

# Answer
# 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(`elem`l)[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.
> 9 votes

# Answer
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.
> 8 votes

# Answer
# (Ab)use the Reader Monad/Applicative

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`.
> 8 votes

# Answer
# 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

```
> 8 votes

# Answer
## 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`.
> 7 votes

# Answer
# 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`.
> 7 votes

# Answer
# 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:

5. If you have `\x -> A B x`, where `x` does not occur in `A`, replace with `(\x -> B) >>= A`.
> 7 votes

# Answer
## 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.
> 7 votes

# Answer
# 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.)
> 6 votes

# Answer
# 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.
> 6 votes

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

```
> 5 votes

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

Instead of using the famous

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

```

in many cases

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

```

works too. and is two bytes shorter.
> 5 votes

# Answer
# 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

```
> 5 votes

# Answer
# 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.
> 5 votes

# Answer
### 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)`.
> 5 votes

# Answer
# 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.
> 5 votes

# Answer
## 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.
> 4 votes

# Answer
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.
> 4 votes

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

```
> 3 votes

# 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 -}

```

(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.
> 3 votes

# Answer
## 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.
> 3 votes

# Answer
# 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"

```
> 3 votes

# Answer
# `iterate` isn't very good

Defining your own function that returns an infinite list is *usually* shorter. Compare:

```
f x=x*x+x;iterate f a
iterate(\x->x*x+x)a
g x=x:g(x*x+x);g a

```

Exceptions include when `f` is a builtin, but remember:

* `iterate pred a` is just `[a,pred a..]`
* `iterate(+k)a` is just `[a,a+k..]`

Sometimes I see people write very "Haskell-y" expressions like:

```
(+5).fst<$>iterate(\(a,b)->(b,a+b+1))(0,1)

```

But this can be golfed down all the way to:

```
a#b=b+5:b#(a+b+1);0#1

```
> 3 votes

# Answer
# Endless `Char` ranges

You can use endless ranges of `Char`s, and they will still be finite, because there are only 1114111 valid Unicode characters:

```
['a'..]

```

producing

```
"abcdefghijklmnopqrstuvwxyz{|}~\DEL\128\129\130\131\132\133\134\135\136\137\138\139\140\141\142..."

```

Attempt This Online!

In many cases where you would otherwise use a range such as `['a'..'z']`, you may be able to leave off the ending item, if you know the input is constrained to a certain set of characters (e.g. only alphanumeric ASCII)
> 1 votes

# Answer
# Avoid Data.List

The function are nice, but imports are costly. If you only need a single function, there are shorter alternatives:

```
import Data.List;intercalate -- too long
c#s=tail$(c:)=<<s            -- nice, especially when inlined
(tail.).(=<<).(:)            -- if you like unreadable mess
(tail.).((c:)=<<)            -- applied to c

```

```
import Data.List;intersperse -- too long
c#s=tail$do d<-s;[c,d]       -- nice
(c:).pure=<<tail             -- a function on the list

```

Check if the challenge allows for leading and/or trailing newlines. You may be able to omit the `tail`.
> 1 votes

---
Tags: code-golf, tips, haskell
---


# Question
Title: Find the indices of values in one list in another
You must take two lists of positive integers as input, let's call these **n** and **m**.

You may assume that:

* All integers in **n** are part of **m**
* All integers in **m** are unique
* The lists are non-empty

### Challenge: Return the indices of where you find the values in **n**, in **m**.

That might be confusing, but I think the test cases will make the task pretty clear. The examples are 1-indexed, you may choose 0-indexed if you want to (please specify).

```
n = 5 3 4 1
m = 6 8 4 1 2 5 3 100
output: 6 7 3 4    // 5 is in the 6th position of m
                   // 3 is in the 7th position of m
                   // 4 is in the 3rd position of m
                   // 1 is in the 4th position of m

n = 5 3 4 9 7 5 7
m = 3 4 5 7 9
output: 3 1 2 5 4 3 4

n = 1 2 3 4 5 6
m = 1 2 3 4 5 6
output: 1 2 3 4 5 6

n = 16 27 18 12 6 26 11 24 26 20 2 8 7 12 5 22 22 2 17 4
m = 15 18 11 16 14 20 37 38 6 36 8 32 21 2 31 22 33 4 1 35 3 25 9 30 26 39 5 23 29 10 13 12 7 19 24 17 34 27 40 28
output: 4 38 2 32 9 25 3 35 25 6 14 11 33 32 27 16 16 14 36 18

n = 54
m = 54
output: 1

```

**The winners will be the shortest solutions in each language.**

---

This is a very nice meta-post by the way!

# Answer
# , 26 bytes

```
jòdf kÄ/-
DÓÓ
ÒC1@"Gòdk

```

Try it online!

This is a very strange and hacky solution, because V has little to no concept of numbers. Input comes in this format:

```
6 8 4 1 2 5 3 100
5 3 4 1

```

With a trailing space on each line.

Hexdump:

```
00000000: 6af2 6466 206b c42f 122d 0a44 d3d3 0ad2  j.df k./.-.D....
00000010: 0143 311b 4022 47f2 646b                 .C1.@"G.dk

```

Explanation:

```
j                   " Move down one line (to N) (1)
 ò                  " Recursively:
  df                "   (d)elete until you (f)ind a space. This will be saved into
                    "   register '-' (2)
     k              "   Move up one line (to M)
      Ä             "   Duplicate line M (3)
       /<C-r>-      "   Move the cursor forward until the next occurence of register '-'
                    "   (the number we deleted from N)
                    "   (4)
D                   "   Delete every character *after* the cursor (5)
 ÓÓ                 "   Remove everything on this line except for whitespace
Ò<C-a>              "   Replace every character on this line with `<C-a>`, which is the
                    "   command for incrementing a number (6)
      C             "   Delete this line into register '"', and enter insert mode
       1<esc>       "   Enter a '1' and return to normal mode
             @"     "   Run register '"' as V code (7)
               G    "   Go to the last line (1)
                ò   " End recursion
                 dk " Delete the last two lines (m and n)

```

If this doesn't make it clearer, here are examples of the buffer during the various stages the loop goes through:

Stage 1 (`|` is the cursor)

```
6 8 4 1 2 5 3 100
|5 3 4 1

```

Stage 2:

```
6 8 4 1 2 5 3 100
|3 4 1

```

Stage 3:

```
|6 8 4 1 2 5 3 100
6 8 4 1 2 5 3 100
3 4 1

```

Stage 4:

```
6 8 4 1 2 |5 3 100
6 8 4 1 2 5 3 100
3 4 1

```

Stage 5:

```
6 8 4 1 2 |
6 8 4 1 2 5 3 100
3 4 1

```

Stage 6:

```
|<C-a><C-a><C-a><C-a><C-a>
6 8 4 1 2 5 3 100
3 4 1

```

Stage 7:

```
|6
6 8 4 1 2 5 3 100
3 4 1

```

Back to stage 1:

```
6
6 8 4 1 2 5 3 100
|3 4 1

```
> 13 votes

# Answer
# Python 2, 25 bytes

```
lambda a,b:map(a.index,b)

```

Try it online!

Note that this uses 0-indexing.
> 9 votes

# Answer
# APL (Dyalog), 1 byte

Try it online!

Note: the  function does **not** take scalars as its left argument, so to give it a left argument like `54`, you have to make it into an array using `,` like so `(,54)`.
> 8 votes

# Answer
## Mathematica, 25 bytes

```
#&@@@PositionIndex@#/@#2&

```

Takes two inputs `m` and `n`, and returns the 1-based indices of `n` in `m`.
> 7 votes

# Answer
# Retina, ~~32~~ ~~31~~ 30 bytes

1 byte saved thanks to Kritixi Lithos and 1 byte thanks to Martin Ender

```
(\d+)(?=.*¶(\d+ )*\1 )
$#2
G1`

```

Uses 0-indexing. Input has a trailing space on each line.

Try it online!

**Explanation**

```
(\d+)(?=.*¶(\d+ )*\1 )
$#2

```

Here we replace every number on the first line by the number of numbers before the same number on the second line.

```
G1`

```

Then, we delete the second line, leaving only the new first line as the output.
> 6 votes

# Answer
# Java, ~~104~~ 81 bytes

1 byte thanks to Business cat.

```
void f(int[]a,int[]b){for(int i=0,j=0;i<b.length;)j=a[j++]==b[i]?0*(b[i++]=j):j;}

```

Try it online!
> 5 votes

# Answer
# C#, 32 Bytes

```
(n,m)=>n.Select(i=>m.IndexOf(i))

```

This is the code as a lambda expression, so it should be valid.

The solution is with a 0 based index. I think it's pretty straigt forward how it works - it simply takes the items of n and selects the indices of the items in m.
> 5 votes

# Answer
# Octave, 25 bytes

```
@(n,m)([x,~]=find(n==m'))

```

Try it online!
> 4 votes

# Answer
# Haskell, 32 bytes

```
a%b=[length$fst$span(/=x)b|x<-a]

```

Try it online! One-indexed.

Other attempts:

```
q(h:t)x|x==h=0|1>0=1+q t x;map.q
f b=map$length.fst.($b).span.(/=)
a%b=[until((==x).(b!!))(+1)0|x<-a]
a%b=[until(\y->x==b!!y)(+1)0|x<-a]
import Data.List;map.flip elemIndex

```
> 4 votes

# Answer
# k, 1

This is a built-in operator in `k` and uses zero-based indexing.

```
?

```

Example:

```
k)6 8 4 1 2 5 3 100 ? 5 3 4 1
5 6 2 3

```
> 3 votes

# Answer
# Jelly, 3 bytes

```
iÐ€

```

Try it online!

## Specs

* Input: two arguments, the first being **m**, and the second being **n**.
* Output: one array
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
v²yk,

```

Try it online!

```
v     # For each value in n (call it y)
 ²    # Push m
  y   # Push y
   k, # Print the 0-indexed index of y in m

```
> 2 votes

# Answer
## JavaScript (ES6), 28 bytes

Takes the arrays in currying syntax `(n)(m)`. 0-indexed.

```
let f =

n=>m=>n.map(v=>m.indexOf(v))

console.log(JSON.stringify(f([5,3,4,1])([6,8,4,1,2,5,3,100])))
console.log(JSON.stringify(f([5,3,4,9,7,5,7])([3,4,5,7,9])))
console.log(JSON.stringify(f([1,2,3,4,5,6])([1,2,3,4,5,6])))
console.log(JSON.stringify(f([16,27,18,12,6,26,11,24,26,20,2,8,7,12,5,22,22,2,17,4])([15,18,11,16,14,20,37,38,6,36,8,32,21,2,31,22,33,4,1,35,3,25,9,30,26,39,5,23,29,10,13,12,7,19,24,17,34,27,40,28])))
console.log(JSON.stringify(f([54])([54])))
```
> 2 votes

# Answer
# Perl 6, 31 bytes

```
->\n,\m{n.map:{m.first($_,:k)}}

```

Try it

## Expanded:

```
-> \n, \m {  # pointy block lambda

  n.map: {            # map over the values in ｢n｣
    m.first( $_, :k ) # return the key ｢:k｣ of the first occurrence
  }
}

```

0 indexed
> 2 votes

# Answer
# R, ~~20~~ 5 bytes

1-indexed; `match` is the builtin function that finds the indices in the second input of the elements of the first, i.e., `match(n,m)` gives the desired answer

```
match

```

thanks to @flodel for pointing out that returning a function is perfectly acceptable as an answer!

Try it online!
> 2 votes

# Answer
# MATL, 2 bytes

```
&m

```

This uses 1-indexing. Try it online!

### Explanation

The meta-function `&` indicates that the next function will use a (function-specific) secondary default in/out specification. For function `m` (`ismember`), `&` specifies that its second output will be produced. This contains the index of (the first occurrence of) each entry of the first input in the second input.
> 2 votes

# Answer
# Japt, 4 bytes

```
m!bV

```

Test it online!

### Explanation

There's not much to explain here, but it shows off an interesting feature of Japt. Normally, you would pass a function to `m`, like so:

```
mX{VbX}

```

This is basically `U.map(X => V.indexOf(X))` (the `U` is implicit). However, when you're just performing one operation between two values (`b` here, on `V` and `X`), you can just give the operator and the other value and Japt will make a function out of it. This means `mX{X+2}` can be golfed to `m+2`.

However, this doesn't work when the values are in the wrong order (`mbV` would be short for `mX{XbV}`). To get around this, you can prepend an exclamation mark to the operator, which tells Japt to swap the operands. This costs an extra byte, but it's still a couple bytes shorter than the alternative. And now you know a little more about Japt.
> 2 votes

# Answer
## Haskell, 34 bytes

```
n#m=[i|a<-n,(i,e)<-zip[1..]m,e==a]

```

Usage example: `[5,3,4,9,7,5,7] # [3,4,5,7,9]` -\> `[3,1,2,5,4,3,4]`

The built-in `elemIndex` is in `Data.List` and therefore longer than the version above. The outer loop goes through `n` and the inner loop through pairs of `(i,e)` where `i` is the index of `e` in `m`. Keep the `i` where `e` equals the current element of `n`.
> 2 votes

# Answer
# Pyth, 4 bytes

```
xLQE

```

Try it online!

Note that this uses 0-indexing.
> 1 votes

# Answer
# , 2 bytes

```
i.

```

This is not a complete program, but a built-in function.

Use it as such:

```
echo 6 8 4 1 2 5 3 100 i. 5 3 4 1

```

Try it online!

Note that this uses 0-indexing.
> 1 votes

# Answer
# CJam, 4 bytes

```
{f#}

```

Anonymous block that expects arguments on the stack and leaves the result on the stack.

Uses 0-indexing.

Try it online!
> 1 votes

# Answer
# PHP, 56 Bytes

Online Versions

0 Indexing

output as String

```
<?foreach($_GET[0]as$v)echo" ".array_flip($_GET[1])[$v];

```

## PHP, 65 Bytes

Output as array

```
<?foreach($_GET[0]as$v)$r[]=array_flip($_GET[1])[$v];print_r($r);

```

PHP, 78 Bytes

workaround with `array_map`

```
<?print_r(array_map(function($v){return array_flip($_GET[1])[$v];},$_GET[0]));

```

for not unique arrays replace with `array_flip($_GET[1])[$v]` `array_search($v,$_GET[1])`
> 1 votes

# Answer
## Haskell, 43 bytes

```
a*b=[[fst x|x<-zip[0..]b,y==snd x]!!0|y<-a]

```

```
a*b=                                         -- define function * with 2 args
    [                                |y<-a]  -- for each elt in first arg
               zip[0..]b                     -- match elts in second arg w/ idxs
                                             -- [a,b,c] -> [[0,a],[1,b],[2,c]]
     [fst x|x<-                  ]           -- take first element in each pair
                        ,y==snd x            -- if the index matches
                                  !!0        -- first element (always only 1)

```
> 1 votes

# Answer
# Perl 5, ~~38~~ 34 bytes

4 bytes saved thanks to Dada

```
sub{map$x{$_}//($x{$_}=++$x)x0,@_}

```

1-indexed. Takes the lists **m** and **n** as a single list, like `f(@m,@n)`. The `x0` is just to keep the output from starting with `1,2,3,4,5`, etc.
> 1 votes

# Answer
## Clojure, 25 bytes

```
#(map(zipmap %2(range))%)

```

0-indexed.
> 1 votes

# Answer
# Uiua, 1 byte

Try it!

0-indexed.
> 1 votes

# Answer
# Bash + coreutils, 51

```
for n in $1
do grep -wn $n <<<"$2"
done|cut -d: -f1

```

Try it online.

---

Previous answer:

```
s()(sort -$1k2)
nl|s|join -j2 - <(nl<<<"$1"|s)|s n|cut -d\  -f3

```

Try it online.
> 0 votes

# Answer
# Java 7, 80 bytes

```
void c(int[]a,java.util.List b){for(int i=0;i<a.length;a[i]=b.indexOf(a[i++]));}

```

0-indexed

**Explanation:**

```
void c(int[]a,java.util.List b){  // Method with integer-array and List parameters
  for(int i=0;i<a.length;         //  Loop over the integer-array
    a[i]=b.indexOf(a[i++])        //   And change every value to the index of the List
  );                              //  End of loop (no body)
}                                 // End of method

```

**Test code:**

Try it here.

```
import java.util.Arrays;
class M{
  static void c(int[]a,java.util.List b){for(int i=0;i<a.length;a[i]=b.indexOf(a[i++]));}

  public static void main(String[] a){
    int[] x = new int[]{ 5, 3, 4, 1 };
    c(x, Arrays.asList(6, 8, 4, 1, 2, 5, 3, 100));
    System.out.println(Arrays.toString(x));

    x = new int[]{ 5, 3, 4, 9, 7, 5, 7 };
    c(x, Arrays.asList(3, 4, 5, 7, 9));
    System.out.println(Arrays.toString(x));

    x = new int[]{ 1, 2, 3, 4, 5, 6 };
    c(x, Arrays.asList(1, 2, 3, 4, 5, 6));
    System.out.println(Arrays.toString(x));

    x = new int[]{ 16, 27, 18, 12, 6, 26, 11, 24, 26, 20, 2, 8, 7, 12, 5, 22, 22, 2, 17, 4 };
    c(x, Arrays.asList(15, 18, 11, 16, 14, 20, 37, 38, 6, 36, 8, 32, 21, 2, 31, 22, 33, 4, 1, 35, 3, 25, 9, 30, 26, 39, 5, 23, 29, 10, 13, 12, 7, 19, 24, 17, 34, 27, 40, 28));
    System.out.println(Arrays.toString(x));

    x = new int[]{ 54 };
    c(x, Arrays.asList(54));
    System.out.println(Arrays.toString(x));
  }
}

```

**Output:**

```
[5, 6, 2, 3]
[2, 0, 1, 4, 3, 2, 3]
[0, 1, 2, 3, 4, 5]
[3, 37, 1, 31, 8, 24, 2, 34, 24, 5, 13, 10, 32, 31, 26, 15, 15, 13, 35, 17]
[0]

```
> 0 votes

---
Tags: code-golf, number
---


title: Make Code Printing X without X

text:
# Question
Title: Make Code Printing X without X
The challenge is simple: write a program which takes in some non-empty string \\$n\\$ consisting of only uppercase and lowercase ASCII letters, and outputs the *code* for a program (in the same language) which takes in no input and outputs \\$n\\$. However, the code your program generates *must not contain \\$n\\$ as a substring*. For example, if your program was in Python, if the input was `"rin"`, your output could not be `print("rin")`, because that contains the string `rin` (twice). One valid output would be, for example, `x=lambda:'r\151n'`.

Some notes:

* Uppercase and lowercase characters are treated as distinct -- e.g. if the input string contains `A`, your generated code can still contain the character `a`.
* Your generated code follows the same restrictions as a standard code golf answer -- e.g. it can be code which defines an anonymous function returning the string, but it cannot work by saving the string into a variable.
* Your submission is scored by the length of the *generating* code, not the *generated* code. In addition, there are no restrictions on the source of the generating program, only the generated.

Standard loopholes are forbidden. As this is , shortest program wins.

# Answer
> 6 votes
# Google Sheets, ~~37~~ ~~50~~ ~~47~~ 41 bytes

`="=символ("&code(A1)&")&"""&mid(A1,2,9^9)`

Put the input in cell `A1` and the formula in `B1`.

The formula assumes that the input string \\$n\\$ consists of uppercase and lowercase *Latin* letters only.

When the input is `rin`, the formula outputs `=символ(114)&"in` which is a valid formula in Google Sheets in any locale, including Latin locales such as United States. When the output is evaluated as formula, its result is `rin`.

Given a single letter such as `A`, the formula outputs `=символ(65)&"` which gives the result `A`.

The formula defends against substrings being part of the output code by not including any Latin letters in the output except those found in input. The first letter is "escaped" by using the equivalent of the `char()` function in Cyrillic, `символ()`, whose name doesn't match any Latin letters (`console.log('символ'.match(/\w/))``null`).

# Answer
> 6 votes
# Python, ~~54~~ 45 bytes

```
lambda x:f'ｅⅺｔ("\%o{x[1:]}")'%ord(x[0])

```

Attempt This Online!

Python lambda that returns a string that has a full Python program to print the string (on stderr). Used full-width characters (which are non-ASCII and so won’t appear in the input). Inspired by @UnrelatedString’s answer to a different question.

*Thanks to @ShadowRanger for saving two bytes, @JonathanAllan for saving a further four and @dingledooper for three more again!*

# , 66 bytes

```
\(x,s=substring)sprintf('\\()"\\%o%s"',utf8ToInt(s(x,1,1)),s(x,2))

```

Attempt This Online!

Equivalent program in R (but returns an anonymous function)

# Answer
> 4 votes
# Ruby, ~~38~~ ~~31~~ 29 bytes

```
->n{"$>.<<''<<"+n.bytes*'<<'}

```

Attempt This Online! Generates string in such a way that it never contains any letters.

-7 bytes from Value Ink and another -2 from ShadowRanger.

# Answer
> 3 votes
# brainfuck, ~~95~~ 63 bytes

*-32 bytes thanks to @emanresu A*

```
--[>+<++++++]>[->+>+<<]>+++>>----[>+<----]>-<,[[-<.>]<<.>>>.<,]

```

Try it online!

Essentially an ultra basic constant string generator. For each character code, outputs `+.[-]` where the `+` is repeated a number of times equal to the byte value of the input.

### With Comments

```
--[>+<++++++]> Load a PLUS
[->+>+<<]   Copy it twice
>+++>       Change the other to a DOT
>----[>+<----]>- Load a RIGHT ANGLE BRACKET
<,[ Main loop WHILE NOT EOF
    [-<.>] Output a plus to increment the accumulator by one
    <<.>>>.< Output a DOT followed by a RIGHT ANGLE BRACKET
,] Repeat

```

# Answer
> 3 votes
# Zsh, 28 bytes

```
<<<'<<<${(#):-'$[#1]\}${1:1}

```

Try it online!

Similar idea to others, convert the first character to its character code, then `${(#):-NUM}` converts it back when evaluated.

# Answer
> 2 votes
# Jelly, ~~5~~ 4 bytes

```
OṾ”Ọ

```

Try it online!

A full program that takes a string and prints a Jelly niladic link that outputs the string.

*Thanks to @JonathanAllan for saving a byte!*

## Explanation

```
O    | Codepoints
 Ṿ   | Uneval (and implicitly print)
  ”Ọ | an "Ọ" (implicitly printed)

```

# Answer
> 2 votes
# Julia 1.0, 40 bytes

```
!s="_->"*join("*('@'+$(i-'@'))" for i=s)

```

Try it online!

builds an anonymous function that concats (`*` in julia) chars together be adding to `'@'` eg `'A'==('@'+1)` without using any letters

for example: `ABC` =\> `_->*('@'+1)*('@'+2)*('@'+3)`

# Answer
> 1 votes
# Uiua, ~~13~~ 10 bytes

```
&p"-1"&s+1

```

Try it online!

(3 bytes saved by using `&s`)

## Explanation

Simply encodes the string by incrementing all codepoints and decrementing in the output program

```
        +1 # increment all codepoints
      &s   # pretty-print (includes quotes)
&p"-1"     # print -1

```

# Answer
> 1 votes
# , 33 bytes

```
-:&'u'{'117{a."_',:~'u:@',3":@u:]

```

Try it online!

A function which outputs the source code of a function which outputs the original input. Since in J no-argument functions don't exist, we call the outputted function with a dummy argument `0` which is ignored.

Probably a better approach out there, but this idea is:

* Return a function which uses "Unicode" `u:` to translate the code points of the original input back to unicode: `u:@<literal list of code points>`.
* Everything is non-letter in that code except for `u`, so that's the one input we need to defend against. So for that specific case we return a function which returns the 117th letter of the J alphabet `a.`, which is also `u` but whose code does not contain `u`: `117{a."_`.

# BQN, 19 bytes

```
""""∾˜"-⟜1∘"""∾+⟜1

```

BQN Online

Bonus my first BQN answer, using a similar code point shift approach as Pseudo Nym's Uiua answer.

Perhaps there is a better way to escape quotes?

# Answer
> 1 votes
# Charcoal, 9 bytes

```
ＦＳ⁺´℅´Ｉ℅ι

```

Try it online! Link is to verbose version of code. Explanation: Prints a list of code points and commands to convert them back into characters. Sample generated program: Try it online!

# Answer
> 1 votes
# PowerShell, ~~30~~ 107 bytes (PS 5/6), 91 bytes (PS 7)

The first attempt, as @nick-kennedy correctly pointed out, didn't account for single character strings.

**PowerShell 5/6**

```
%{If($_[1]){"'$(($_|% T*y)-join"'+'")'"}Else{"[$(If('char'|% Con* $_){'CHAR'}Else{'char'})]$(1*[char]$_)"}}

```

Input comes from the pipeline
Try it online!

**PowerShell 7**
PowerShell 7 (TIO is still on PS6) supports the ternary operator "?:", which allows to get rid of the two If/Else:

```
%{($_[1])?"'$(($_|% T*y)-join"'+'")'":"[$(('char'|% Con* $_)?'CHAR':'char')]$(1*[char]$_)"}

```
* If the input is longer than 1 character: Breaks the input string into single characters and generates code to add them back together: `'r'+'i'+'n'`
* If the input is only one character: Casts the codepoint using either \[char\] or \[CHAR\], depending on the case of the character: `[char]65` or `[CHAR]97`.

Output in PowerShell is implicit.
**Ungolfed:**

```
ForEach-Object {  # Takes input from the pipeline
    If ($_.Length -gt 1) {
        # $(...) is a subexpression which will be evaluated inside a string enclosed in double quotes
        # Turn the string to an array of characters, then join them back with the literal '+'
        "'$(($_ | ForEach-Object -MemberName ToCharArray) -join "'+'")'"
    } Else {  # single char
        # If the character is one of the critical chars (used to cast) is in lowercase, use uppercase for the [char] cast
        # 1*[char]$_: Multiplying an integer with a character will return the codepoint; shorter than [int][char]$_
        "[$(If ('char'.Contains($_)) {'CHAR'} Else {'char'})]$(1*[char]$_)"
    }
}

```

Test it in PowerShell 7 (can be pasted into a PS7 console):

```
$testcases = 'Hello World', 'char', 'a', 'A', 'b', 'B'
$codes = $testcases |
%{($_[1])?"'$(($_|% T*y)-join"'+'")'":"[$(('char'|% Con* $_)?'CHAR':'char')]$(1*[char]$_)"}
For ($i = 0; $i -lt @($testcases).Count; $i++) {
    "String input:   $(@($testcases)[$i])"
    "Generated code: $(@($codes)[$i])"
    "Executed code:  $(Invoke-Expression -Command @($codes)[$i])"
    '--'
}

```

# Answer
> 1 votes
# JavaScript (V8), ~~57~~ 52 bytes

*-5 bytes thanks to @Arnauld*

There was a shorter way

```
s=>`_=>"\\${s.charCodeAt().toString(8)+s.slice(1)}"`

```

The smallest representable Octal letter is `A` at `101`, which means we don't actually need to pad this.

Try it online!

# Answer
> 1 votes
# Retina, 39 bytes

```
T`Ll`lL
$
¶T`?-[_-{`_-{?-[
^t¶T
t¶Y
^
¶

```

Try it online! Explanation: Toggles the case of the input, then appends a command to toggle the case back. This command is normally `T`, but in the event that the input was `T`, uses the `Y` command instead, which has the same effect on a single character. Sample generated program: Try it online!

# Answer
> 1 votes
# Python, 67 bytes

```
lambda s:[p:="print","lambda:"][s in p]+f"('\%o{s[1:]}')"%ord(s[0])

```

Attempt This Online!

## Explanation

```
# if the input is a sub-string of print create a lambda function
#  otherwise create a print statement
[p:="print","lambda:"][s in p]
# replace first character to octal escape sequence
f"('\%o{s[1:]}')"%ord(s[0])

```

A string cannot be a sub-string of both `print` and `lambda:` so the input is not contained in the first half.
By replacing the first character with a number it is guaranteed that the string is not a sub-string of the second half (the string contains only letters).
Both parts are separated by `(` which is guaranteed to not be in the input

---

# Python, 87 bytes (ASCII only)

*can handle empty string*

```
lambda s:[l:="lambda:","print"][s in l]+"('%s')"%f"\%o{s[1:]}"%ord(s[0])if len(s)else""

```

Attempt This Online!

# Answer
> 0 votes
# JavaScript (V8), 96 bytes

*-3 thanks to @Shaggy*
*-6 thanks to @tsh*

I overlooked the rule allowing anonymous functions, so this generates a full program using either `print` or `console.log` with extra precaution for `n` which is present in both instructions.

```
s=>`${S="print",S.match(s)?'co\\u006esole.log':S}("\\${s.charCodeAt().toString(8)+s.slice(1)}")`

```

Try it online!

# Answer
> 0 votes
# ARBLE, 28 bytes

```
'"\\%s"'%(byte(s)..sub(s,2))

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
Ç„)ç)»

```

Output of the output program is a list of characters.

Try it online.
Try the outputted program.

**Explanation:**

```
Ç       # Convert the (implicit) input-string to a list of codepoint-integers
 „)ç    # Push string ")ç"
    )   # Wrap all values on the stack into a list
     »  # Join the inner list by spaces and then the strings by newline
        # (after which the result is output implicitly with trailing newline)

```

Minor note: the second `)` cannot be the more straight-forward  (pair) nor `ª` (append to list), because `„)ç‚` and `„)çª` would be interpret as dictionary words `") reservoir"` and `") baghdad"` respectively.

---
Tags: code-golf, code-generation
---


# Question
Title: Produce the shortest suffix for an (almost) arbitrary string
I encountered some silly code from a game and I figured this would actually turn into a fun golfing problem, so:

Given any ASCII string in the limited char range specified below.

Append as few characters as possible such that, given:

```
i = 1
sum = 0
for char in string
  sum += char.intval * i++
end for

```

`sum % 1000 == 0`

Where `intval` is the ASCII value of the character.

Both the string prefix and your permitted chars are: `A-Z a-z 0-9 . _`

You may assume the numeric result of the pseudo-code above is a number that fits within an unsigned 32-bit int (i.e. no input will be given that causes `sum` to exceed 2^32-1 after appending the minimum possible chars to satisfy `sum`)

You may choose to output the input concatenated with your calculated suffix string, or just your suffix string as you prefer.

## Example

Given the input `ddd` the shortest solution would be appending one more `d` because `(100 + (100*2) + (100*3) + (100*4)) % 1000 == 0`

# Answer
# Charcoal, 38 bytes

```
⊞υωＦυ¿¬ⅈ¿﹪ΣＥ⁺θι×⊕λ℅κφＦΣ⟦αβ⭆χκ._⟧⊞υ⁺ικι

```

Try it online! Link is to verbose version of code. Explanation:

```
⊞υωＦυ

```

Start a breadth-first search with an empty suffix.

```
¿¬ⅈ

```

Check that a solution hasn't yet been found.

```
¿﹪ΣＥ⁺θι×⊕λ℅κφ

```

If the input plus current suffix is not a multiple of `1000`, then:

```
ＦΣ⟦αβ⭆χκ._⟧

```

Loop over all valid characters.

```
⊞υ⁺ικ

```

Append the character to the suffix and add this to the list of suffixes to check.

```
ι

```

But if it is then output the suffix as the solution.

Would be only 36 bytes to output the full string:

```
⊞υＳＦυ¿¬ⅈ¿﹪ΣＥι×⊕λ℅κφＦΣ⟦αβ⭆χκ._⟧⊞υ⁺ικι

```

Try it online! Link is to verbose version of code.
> 2 votes

# Answer
# Python, 147 bytes

*-7 bytes, thanks to STerliakov*

```
def f(s,q="",Q=[]):
 while(i:=0)+sum((i:=i+1)*ord(c)for c in s+q)%1000:*Q,q=[q+c for c in{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}]+Q
 return q

```

Attempt This Online!

`{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}` produces an iterable of the allowed characters by taking all ASCII-characters form `.` to `z` (smallest and largest allowed character) and the removing the additional characters.
Using the standard library would take the same amount of characters: `from string import*` `"._"+digits+ascii_letters`

---

# Python, 140 bytes

```
def f(s,Q=[]):
 while(i:=0)+sum((i:=i+1)*ord(c)for c in s)%1000:*Q,s=[s+c for c in{*map(chr,range(46,123))}-{*"/:;<=>?@[\\]^`"}]+Q
 return s

```

Attempt This Online!

---

# Python, 129 bytes

*suggested by STerliakov, uses binary strings instead of strings*

```
def f(s,Q=[]):
 while(i:=0)+sum(c*(i:=i+1)for c in s)%1000:*Q,s=[[*s,c]for c in{*range(46,123)}-{*b"/:;<=>?@[\\]^`"}]+Q
 return s

```

Attempt This Online!
> 2 votes

# Answer
# JavaScript (Node.js), 121 bytes

*-3 thanks to @tsh*
*-3 thanks to @l4m2*

```
s=>{for(B=Buffer,g=n=>S=n?B([n&127])+g(n>>7):"",n=0;B(s+g(n++)).map(c=>t+=c*++i,i=t=0),t%1e3|/[^\w.]/.test(S););return S}

```

Try it online!

Or **118 bytes** if we can return the full string instead of just the suffix.

### Commented

```
s => {               // s = input string
  for(               // loop:
    B = Buffer,      //   B = alias for Buffer
    g =              //   g is a recursive helper function
    n =>             //   taking n = integer encoding the suffix
      S =            //     save the suffix in S
      n ?            //     if n is not 0:
        B([n & 127]) //       append the char. with ASCII code n & 127
        + g(n >> 7)  //       and do a recursive call with n >> 7
      :              //     else:
        "",          //       stop
    n = 0;           //   start with n = 0
    B(               //   get the ASCII codes of:
      s +            //     the input string
      g(n++)         //     followed by the suffix computed with g(n)
    )                //     (increment n afterwards)
    .map(c =>        //   for each ASCII code c:
      t += c * ++i,  //     increment i and add c * i to t
      i = t = 0      //     start with i = 0 and t = 0
    ),               //   end of map()
    t % 1e3 |        //   continue while t is not divisible by 1000
    /[^\w.]/         //   or there is an invalid character ...
    .test(S);        //   ... in the suffix
  );                 // end of for()
  return S           // return the suffix
}                    //

```
> 1 votes

# Answer
# Scala 2, ~~153~~ ~~142~~ 136 bytes

```
s=>{def z:Stream[String]=s#::z.flatMap(x=>'.'to'z'diff "/:;<=>?@[\\]^`"map(x+))
z.find(_.zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000<1)}

```

Attempt This Online!

Recursively constructs an infinite Stream of possible suffixes and chooses the first with the correct sum. They iterate from shortest to longest, so it produces the correct output.

## Alternative Solution, ~~158~~ 139 bytes:

```
s=>Stream.iterate(Seq(s))(_.flatMap(s=>'.'to'z'diff "/:;<=>?@[\\]^`"map(s+))).flatten.find(_.zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000<1)

```

Same idea as above, without a recursive function. Sadly, `Stream.iterate` and `flatten` is very verbose.
> 1 votes

# Answer
# Jelly, 26 bytes

```
ṃØW;”.¤Ḋ
Ç;@O×JSƊȷḍ
0ç1#ḢÑ

```

Try it online!

A full program that takes a string argument and implicitly prints the suffix needed.

*Thanks to Neil for pointing out a problem related to base decompression, now fixed (at a cost of two bytes and a 64-fold efficiency penalty!*

## Explanation

```
ṃØW;”.¤Ḋ     # Helper link 1: takes an integer and generates a suffix
ṃ            # Base decompress into:
 ØW;”.¤      # - Word characters (A-Za-z0-9_) concatenated to "."
       Ḋ     # Remove first character (avoids issue related to suffixes that start with .)

Ç;@O×JSƊȷḍ  # Helper link 2: Takes an integer as left argument and the original string as right argument and returns 1 if it meets the requirements and zero if not
Ç           # Call helper link 1
 ;@         # Concatenate the output of this to the original string
   O        # Codepoints
       Ɗ    # As a monadic chain:
    ×J      # Multiply by indices
      S     # Sum
        ȷḍ  # Divisible by 1000

0ç1#ḢÑ       # Main link: takes a string as its argument and returns the suffix needed
0ç1#         # Starting with zero, find the first integer that when called into helper link 2 returns truthy
    Ḣ        # Head (since # returns a list)
     Ñ       # Call helper link 1 to regenerate the suffix

```

Created with the help of Luminespire.
> 1 votes

# Answer
# 05AB1E, 19 bytes

```
žj'.«∞δã˜õš.Δ«ÇƶO₄Ö

```

Try it online or verify some more test cases.

**Explanation:**

```
žj          # Push builtin string "ab...yzAB...YZ01...89_"
  '.«      '# Append an "."
     ∞      # Push an infinite positive list: [1,2,3,...]
      δ     # Use each integer in this list as separated argument on the string:
       ã    #  Cartesian power
        ˜   # Flatten this list of lists of strings
         õš # Prepend an empty string ""
.Δ          # Pop and find the first value that's truthy for:
  «         #  Append the current potential suffix to the (implicit) input-string
   Ç        #  Convert it to a list of codepoint-integers
    ƶ       #  Multiply each integer by its 1-based index
     O      #  Sum the list together
      ₄Ö    #  Check whether this sum is divisible by 1000
            # (after which the found result is output implicitly)

```
> 1 votes

# Answer
# Scala, ~~267~~ 190 bytes

A port of @bsoelch's Python answer in Scala.

Saved 77 bytes thaks to @corvus\_192

---

Golfed version. Attempt this online!

```
s=>{var(a,z,l)=(Seq[String](),"",".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
val V=l+l.toLowerCase
while(0<(s+z).zipWithIndex.map{case(c,j)=>j*c+c}.sum%1000){a=a.drop(1)++V.map(z+);z=a.head}
z}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(f(""))
    println(f("Test"))
    println(f("Hello World"))
    println(f("235711"))
  }

  def f(s: String, q: String = "", i: Int = 0, Q: List[String] = List(), l: String = ".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): String = {
    val lLower = l + l.toLowerCase
    var QNew = Q
    var qNew = q
    var iNew = i
    while ((s + qNew).map(_.toInt).zipWithIndex.map { case (c, ind) => (ind + 1) * c }.sum % 1000 != 0) {
      QNew = QNew.drop(1) ++ lLower.map(qNew + _)
      qNew = QNew.head
      iNew = 0
    }
    qNew
  }
}

```
> 0 votes

# Answer
# Go, ~~309~~ 305 bytes

Saved 4 bytes thanks to the comment of @ceilingcat

---

Golfed version. Attempt This Online!

```
func f(s string)string{return g(s,"",0,[]string{},".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")}
func g(s,q string,i int,Q[]string,l string)string{l+=strings.ToLower(l);for{r:=0
for i,c:=range s+q{r-=^i*int(c)};if r%1000<1{break};if len(Q)>1{Q=Q[1:]};for _,c:=range l{Q=append(Q,q+string(c))};q=Q[0]};return q}

```

Ungolfed version. Attempt This Online!

```
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(fWithDefaults(""))
	fmt.Println(fWithDefaults("Test"))
	fmt.Println(fWithDefaults("Hello World"))
	fmt.Println(fWithDefaults("235711"))
}

func fWithDefaults(s string) string {
	return f(s, "", 0, []string{}, ".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
}

func f(s string, q string, i int, Q []string, l string) string {
	lLower := l + strings.ToLower(l)
	var QNew = Q
	var qNew = q
	for {
		var sum int
		for ind, c := range s + qNew {
			sum += (ind + 1) * int(c)
		}
		if sum%1000 == 0 {
			break
		}
		if len(QNew) > 1 {
			QNew = QNew[1:]
		}
		for _, c := range lLower {
			QNew = append(QNew, qNew+string(c))
		}
		qNew = QNew[0]
	}
	return qNew
}

```
> 0 votes

---
Tags: code-golf, string, math
---