[Question]
      [
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](https://codegolf.meta.stackexchange.com/a/11935/56433)**. There is also a dedicated Haskell chat room: [Of Monads and Men](https://chat.stackexchange.com/rooms/66515/of-monads-and-men).

[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](https://github.com/lambdabot/lambdabot/blob/1d1ed3e7980081c9f356f8d2fd8ca2771c0ed4f4/lambdabot/State/Pristine.hs.default), which includes, among other things, `Control.Arrow`, `Data.Bits`, `Data.Ratio`, `System.Random` and `{-# LANGUAGE ParallelListComp #-}` - go wild!
[Answer]
## Replace `let` by lambda
This can usually shorten a lone auxiliary definition that can't be [bound with a guard](https://codegolf.stackexchange.com/a/76749/32014) 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.
[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](https://hackage.haskell.org/package/base-4.14.1.0/docs/Data-List.html). 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.
[Answer]
# Online Tools
* [**Try it online!**](https://tio.run/#haskell)
TIO supports online compilation of Haskell code with the [GHC 8.0.2](https://www.haskell.org/ghc/download_ghc_8_0_2.html) 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**](http://pointfree.io/)
Converts Haskell code to pointfree Haskell code which sometimes is shorter, see [this tip](https://codegolf.stackexchange.com/a/19260/56433).
Note: When dealing with functions that take two or more arguments, the pointfree version generated by *pointfree.io* often includes the [`ap`](http://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#v: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`](http://hackage.haskell.org/package/base-4.11.0.0/docs/Control-Monad.html#v: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`](https://chat.stackexchange.com/transcript/66515?m=41076361#41076361).
* [**pointfree.pages.dev**](https://pointfree.pages.dev) is an alternative site for pointfree.io (which is down at the time of editing).
* [**Hoogle**](https://www.haskell.org/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.
[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.](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8tVYRvzPzq6zEpDXUHdRiXaUE8vMalYIS9Ws6bMRlfJ0MjYxNTM3MLSQCnWzs42M6Umz0Y3WtdCT88iNvZ/bmJmnoKtQkFpSXBJkU@egopCaV5OZl5qsULFfwA)
[Answer]
# (Ab)use the Reader Monad/Applicative
There already are comments on [pointfree code](https://codegolf.stackexchange.com/a/144658/42833) 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](https://codegolf.stackexchange.com/a/188695/42833)
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](https://codegolf.stackexchange.com/a/188639/42833).
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`.
[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
```
[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](https://codegolf.stackexchange.com/questions/73305/find-the-missing-number-in-an-undelimited-string/73321#73321), [here](https://codegolf.stackexchange.com/questions/98252/pairable-strings/98271#98271) and [here](https://codegolf.stackexchange.com/questions/45496/insertspacesbetweenwords/45498#45498)).
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`.
[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`.
[Answer]
# Converting to Pointfree
As @Laikoni [mentioned in this post](https://codegolf.stackexchange.com/a/107238/24877), you can use [pointfree.io](http://pointfree.io/) to convert your code to pointfree code. However, if you want to do this conversion manually you can check out [this answer](https://stackoverflow.com/a/29596461/2913106) on stackoverflow by [@luqui](https://stackoverflow.com/users/33796/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`.
[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](https://en.wikipedia.org/wiki/Greatest_common_divisor#:%7E:text=In%20mathematics%2C%20the%20greatest%20common,8%20and%2012%20is%204.) 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](https://hackage.haskell.org/package/Unique-0.4.7.8/docs/Data-List-Unique.html) will match the original code's result.
[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.)
[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.
[Answer]
# Use [`Data.Lists`](https://hackage.haskell.org/package/lists-0.4.2/docs/Data-Lists.html)
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])]
```
[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.
[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.
[Answer]
# Haskell + `plumbers`
Use the [plumbers](https://hackage.haskell.org/package/plumbers-0.0.3) 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
```
[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)`.
[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.
[Answer]
## Fixity declarations are your friends
As we know it is often cheaper to define an operator instead of a function (see [this tip](https://codegolf.stackexchange.com/a/19259/56433)), 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](https://codegolf.stackexchange.com/a/154348/48198) answer.
[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.
[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]
```
[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.
[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](https://codegolf.stackexchange.com/a/85910/69655) 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.
[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"
```
[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
```
[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!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWW3ITM_MUbBUKijLzShSi1RPV9fRiIVJQFTCVAA)
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)
[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`.
]


[Question]
      [
You will be given a string `s`. It is guaranteed that the string has equal and at least one `[`s and `]`s. It is also guaranteed that the brackets are balanced. The string can also have other characters.
The objective is to output/return a list of tuples or a list of lists containing indices of each `[` and `]` pair.
### note: The string is zero-indexed.
Example:
`!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]` should return
`[(8, 41), (20, 33), (21, 27), (36, 39), (42, 48), (49, 50)]` or something equivalent to this. Tuples are not necessary. Lists can also be used.
Test cases:
```
input:[[asdf][][td([)ty54g% ]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]
output:[(0, 62),(1, 6), (7, 8), (9, 56), (13, 22), (25, 30), (26, 28), (31, 52), (33, 47), (34, 38), (39, 43)]
input:[[][][][]][[][][][[[[(]]]]]))
output:[(0, 9), (1, 2), (3, 4), (5, 6), (7, 8), (10,26),(11, 12), (13, 14), (15, 16), (17, 25), (18, 24), (19, 23), (20, 22)]
input:[][][[]]
output:[(0, 1), (2, 3), (4, 7), (5, 6)]
input:[[[[[asd]as]sd]df]fgf][][]
output:[(0, 21), (1, 17), (2, 14), (3, 11), (4, 8), (22, 23), (24, 25)]
input:[]
output:[(0,1)]
input:[[(])]
output:[(0, 5), (1, 3)]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each programming language wins.

[Answer]
# [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak), 108 bytes
```
{((((((([][][]){}){}){}()){}){}{}[])()()){{}<>{}(<>)}{}((){[](<{}>)}{}){{}<>[({}<[{}]>)](<>)}{}<>(({}()))<>}
```
[Try it online!](https://tio.run/##LU07DsMgDL1Klkr2kKnphriI5YEGGdKiDiEdKouzEwj1V@8j@7m77TNLcu9aFUYQ90QtowDH1tJIwA61GNsEY7GxAKjEYLRccKgEbZIWtsh/n7EA1zU0ttRK5LKX/urwQHj8Hku4TRwDkfCXSYheMTAF8dyNrTOH6Fn25S5cZ5emNbmct/UE "Brain-Flak – Try It Online")
Stores each opening `[` in the right stack, and outputs whenever we hit a `]`.
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
s=[];i=0
for c in input():
 if'['==c:s+=i,
 if']'==c:print s.pop(),i
 i+=1
```
[Try it online!](https://tio.run/##HYo7DsMgFAR7n4ImAmQrysdpHHGS1SsiowekwAhw4dMTYmm2GO2ko/otPlorBvQO5jbwlsUqQuykvSq9DCKwhDRmXcpownQ6nZ5yiFWUa9qS0lPoz2jurUngUywTCNUq6Hq8ZncR5B3AtBMY@HpHcGzpH/YVct4S5/nJJH8 "Python 2 – Try It Online")
[Answer]
# JavaScript, ~~69~~ 62 bytes
A quick bit of golf on the train home. Can probably be improved on.
Takes input as an array of characters and outputs an object with the keys being the indices of the `[`s and their values being the indices of their corresponding `]`s.
```
a=>a.map((x,y)=>x==`]`?o[a.pop()]=y:x==`[`&&a.push(y),o={})&&o
```
[Try it online](https://tio.run/##FcqxCoMwFEDRXylCQwI2S@1SiN07tEPHxwOD8UXFmmC0GEq/PdXhLofb648O9dT5@TQ60yRSSatSy7f2nK95FKpclaqwujnQ0jvPBap43Q0qxjZaQsujyJ36/gRjLtVuDG5o5OAsv7@eDxnmqRttR5ETByllBqCDIQSE2XAQc7wU9njA1gIQLggE0LcWwZLBfdwKaFuDNBVnwgyFEOkP)
[Answer]
# [Haskell](https://www.haskell.org/), ~~92~~ 79 bytes
```
g(u:a)n(']':x)=(u,n):g a(n+1)x
g a n(s:x)=g([n|s=='[']++a)(n+1)x
g[]_[]=[]
g[]0
```
[Try it online!](https://tio.run/##NYpBCsIwEEX3PUUoQmaIC90G5iSfQWbRxmIdxLTQhXePcSG8xXv8f7f6mNa1tUJ7NnaKGvPBQvvZOZdg5OnKx9AtONXfVAj@qSIRUVMy/j@gN6hAh1m6X9rTFpfXe/HtNI/QbUIAoNrR2jtAx/YF "Haskell – Try It Online")
## Explanation
We create a function `g` which takes 3 arguments.
* `a`, which is the locations of all unmatched `[`s.
* `n`, which is the number of characters processed
* `x` which is the characters unprocessed.
If our first character is `]` we remove `u` from the front our `a` and return `(u,n)` plus whatever else remains.
```
g(u:a)n(']':x)=(u,n):g a(n+1)x
```
If our first character is not `]`, that is either `[` or something else, we increment `n` and add `[n|s=='[']` to the front of `a`. `[n|s=='[']` will be `[n]` if `s=='['` and `[]` otherwise.
```
g a n(s:x)=g([n|s=='[']++a)(n+1)x
```
If we are out of characters we return the empty list.
```
g[]_[]=[]
```
[Answer]
# Java 10, 95 bytes
A void lambda taking the input string as an `int[]` of Unicode code points.
```
s->{int r=0,w=0;for(var c:s){if(c==91)s[w++]=r;if(c==93)System.out.println(s[--w]+","+r);r++;}}
```
[Try It Online](https://tio.run/##XY/BasMwEETP9lcIQ0HCsUhJemhdB0rPhUKOyx5UyVLkOlKQ5IQQ/O2uAjn1sAw77AxvB3EWzaB@l9P0M1pJ5ChiJF/COnIri4cZk0hZtHViJENO8CnZkevJyWS945/exenYh3frEuCOaNKVS2x2t7yT0K1Xl27dah/oWQQi3yK7WU1l170@swiXusYutA9nw/bXmPoj91Pip5ALRkcjNM0F62pV1YG1oa7beV7Koi3/E569VeSY4ek@5awBJCKYyO6/FJoLKftTohWAiEojICRFgaXry9Y8ETwYAI0TggYYDgbBaIX3wzwRzUGhDtuNxopLr/pvn@EiZTz5jxDElTLWlsVczuXyBw)
## Ungolfed
```
s -> {
    int r = 0, w = 0;
    for (var c : s) {
        if (c == 91)
            s[w++] = r;
        if (c == 93)
            System.out.println(s[--w] + "," + r);
        r++;
    }
}
```
## Acknowledgments
* thanks to Jonathan Frech for the idea of using the input string as a stack ([here](https://codegolf.stackexchange.com/a/166464/44945))
[Answer]
# vim, 89 bytes
```
:s/\(.\)/\1<C-V><C-M>/g|g/^\[/ :norm %mm%:pu! =line('.').','.line(\"'m\")<C-V><C-M><C-X>$<C-X>J
:v/\[/d|%s/\[//g
```
## Annotated
```
:s/\(.\)/\1<C-V><C-M>/g            " one character per line
|g/^\[/                            " for each opening square bracket:
  :norm %mm%                       "   mark the line with the matching bracket
  :pu! =line('.').','.line(\"'m\") "   write the line numbers to preceeding line
  <C-V><C-M><C-X>$<C-X>J           "   convert to 0-based counting and join lines
:v/\[/d                            " remove all non-opening bracket lines
|%s/\[//g                          " remove brackets
```
`<C-V>` is 0x16. `<C-M>` is 0x0d. `<C-X>` is 0x18.
[Try it online!](https://tio.run/##HctLCsMgFEDRuQsIGZpQMYHio7ShIHQD3cLTjIy2QZOiSTrJ3u1ndDmDu@UsE6hGqBbUqSDgdge9QqBymmOgLAQmX2tFb/45DQ0XvBX8yMVfquZB1W1BykN5J3KD72d2ln4FR3Ou@kuXjDX4GLyf6XuO3iCa0a6LZuzcXXWKOFqdNKa4GKdRfwA "V – Try It Online")
[Answer]
## QBasic (QB64), ~~137~~ ~~127~~ 112 bytes
```
INPUT a$
for i=0to len(a$)
c$=mid$(a$,i+1,1)
if"["=c$then
b(n)=i
n=n+1
elseif"]"=c$then
n=n-1
?b(n),i
endif
next
```
We need ~~four~~ two bytes because the challenge requires 0-indexing. My first QBasic post, feedback is appreciated.
* 10 bytes thanks to steenbergh
* 3 bytes thanks to Erik the Outgolfer
* 12 bytes by saving in unix file format (`\r\n` -> `\n`)
Looks like this when executed:
[![How it looks](https://i.stack.imgur.com/Wypko.png)](https://i.stack.imgur.com/Wypko.png)
[Answer]
# Pyth, 26 bytes
```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
```
[Try it here](http://pyth.herokuapp.com/?code=VQIqN%5C%5B%3D%2BYZ%29IqN%5C%5D%2C.%29YZ%29%3DhZ&input=%22%5B%5Basdf%5D%5B%5D%5Btd%28%5B%29ty54g%25%20%5Dhg%5B%5Bf%5Du%5D%5Bf%5B%5Bjhg%5D%5Bgfd%5Dsdf%5Dsdfs%5Dghd%5Dfr43f%5D%22&debug=0)
### Explanation
```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
VQ                     =hZ   For each character in the input (indexed by Z)...
  IqN\[=+YZ)                 ... if the character is [, add the index to Y...
            IqN\],.)YZ)      ... if the character is ], output the previous index
                             and current index.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 bytes
*Saved 1 byte thanks to @user202729 informing me that `µ€` is `)`*
```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq47PCP60NZDmx/uWHyk@/A@IC9e/@HuJQ93d2tGPWqY@f//f/Xo6MTilLTY6NjokhSNaM2SSlOTdFWF2Iz06Oi02NLY6LTo6KyM9Njo9LSUWJBCIC6OTc9IiU0rMjFOi1UHAA "Jelly – Try It Online")
After wrestling with this for several hours just to get it working... I'm honestly surprised that it's gotten this short :-)
### Explanation
```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’   Main link. Argument: s (string)  '[a[b]c[]][d]'
  Ø[                 Shortcut for the string "[]".
 Ɱ                   For each char in the "[]":
ẹ                      Find the indices of each occurrence in the input.
                     For our example, this gives the array [[1, 3, 7, 10], [5, 8, 9, 12]].
    µ                Begin a new monadic chain, with said array as its argument.
               )     For each of the two sub-arrays q within the array:
                         [[1, 3, 7, 10], [5, 8, 9, 12]]
     ³ḣ                For each item n in q, take the first n chars of the input.
                         [['[',     '[a[',      '[a[b]c[',   '[a[b]c[]]['],
                          ['[a[b]', '[a[b]c[]', '[a[b]c[]]', '[a[b]c[]][d]']]
        þØ[            For each string s in this, and each char c in "[]":
       ċ                 Count the occurrences of c in s.
                         [[[1, 0],  [2, 0],     [3, 1],      [4, 3]],
                          [[2, 1],  [3, 2],     [3, 3],      [4, 4]]]
           _/          Reduce each pair by subtraction. This is the number of open brackets
                         at each position.
                         [[1, 2, 2, 1], [1, 1, 0, 0]]
             U         Sort the indices by their values, using position as a tiebreaker.
                         [[1, 4, 2, 3], [3, 4, 1, 2]]
              ị        Index these values back into q.
                         [[1, 10, 3, 7], [9, 12, 5, 8]]
               )     Start a new monadic chain with the result as its argument.
                Z    Zip; transpose rows and columns.
                         [[1, 9], [10, 12], [3, 5], [7, 8]]
                 ’   Decrement; switch to 0-indexing.
                         [[0, 8], [9, 11], [2, 4], [6, 7]]
```
[Answer]
# [R](https://www.r-project.org/), ~~141 133 115 112~~ 108 bytes
```
function(y,x=utf8ToInt(y)){for(i in seq(x)){if(x[i]==91)F=c(i,F);if(x[i]==93){T=c(T,F[1],i);F=F[-1]}};T[-1]}
```
[Try it online!](https://tio.run/##RcixCsIwEADQXzktQgLtUFRUStaAeyePE6TJ2UhJMEmxIn57FRenBy/OrGYefZdd8OJZTmrMvG/D0WfxlPLFIQoHzkOydzF9w7GY0JFSh1pq1QlXatn8cy1f7XfbUmNNpZONVhqrmt7vpv05s1guzpttMmywt8MQ4BHiYBDNjcdMq9V6u6MU8caUCFPM5kpISwkV1ABFUcDJxlA5b@wEF842Qu4t8KXL8wc "R – Try It Online")
Nothing special. 1-indexed, because I said so. R doesn't really have stacks, so I originally used `c`, `head`, and `tail` to get the same literal effect. Ungolfed original version (updates using `utf8ToInt` to remove some bytes, using the start of the vector as the top of the stack, and abusing `T` and `F` builtins to avoid initializing the stacks.):
```
f <- function(y, x=el(strsplit(y,""))) {
  p <- l <- NULL
  for(i in seq_along(x)) {
    if(x[[i]]=='[') {
      p <- c(p, i)
    }
    if(x[[i]]==']') {
      l <- c(l, tail(p, 1), i)
      p <- head(p, -1)
    }
  }
  l # Because I said so. Change to l-1 if you want to check the test cases.
}
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 75 bytes
```
: f 0 do dup i + c@ dup 91 = if i s>f then 93 = if f>s . i . cr then loop ;
```
[Try it online!](https://tio.run/##JYpBCsIwFESvMhQERSxK66KKxXt8/kIaJ6mIKUm68PQxtYthhveGPiR3sFwq5wuII4yHmSeM2GO4/2d3wg0jC4o9kdzzg65ZEfuIuogaQ1jN2/sJ1xwriDyioYpKMlvZpe@5tRuosyLUWYUiL2dVLI0ux5Ko1hllaBtqBeYf "Forth (gforth) – Try It Online")
Abuses the floating-point stack, but allows using a `do loop` since the code doesn't (manually) touch the return stack.
### Explanation
1. Loop through characters in string
2. Check each character
	1. If equal to `[`, put on floating point stack
	2. if equal to `]` pop from floating point stack and output with current position
### Code Explanation
```
0 do                 \ start a loop from 0 to string-length
  dup                \ duplicate the starting address to avoid losing it
  i + c@             \ get the address of the current position and retrieve the character
  dup                \ duplicate the character, to allow checking twice
  91 = if            \ if char = [
    i s>f            \ store the current address on the floating point stack
  then               \ end the if-statement
  93 = if            \ if char = ]
    f>s .            \ pop the starting position from the float-stack and print
    i .              \ print the current position
    cr               \ output a newline
  then               \ end the if-statement
loop                 \ end the loop
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
L$v`\[((\[)|(?<-2>])|[^]])*
$.`,$.>`
```
[Try it online!](https://tio.run/##K0otycxLNPz/30elLCEmWkMjJlqzRsPeRtfILlazJjouNlZTi0tFL0FHRc8u4f9/xTgT0@KUtJTojNScnHyF8vyinJTo6JSstNKSWFVVY1Pz2OKi6Ky02OLY6OKikpT02OhYAA "Retina – Try It Online") Explanation:
```
L
```
Generate a list from the match results.
```
$
```
Use the following substitution to generate the list instead of the matches.
```
v`
```
Allow matches to overlap.
```
\[((\[)|(?<-2>])|[^]])*
```
This is an application of .NET's balancing groups. The `[` is matched literally, then as many characters as possible are consumed. As each subsequent `[` is matched, the match is added to the `$2` stack. If that stack isn't empty, we can then match a `]`, removing the match from the stack. Otherwise, we can match anything that's not a `]` (the `[` was already matched earlier). The match stops when it meets the matching `]` for the `[`, since the `$2` stack is (now) empty at that point.
```
$.`,$.>`
```
The substiution consists of two variables separated by a comma. The `.` indicates that the length of the variable, rather than its value, be used. The `>` indicates that the variable should be evaluated in terms of the right-hand separator rather than the match. The `$`` variable refers to the prefix of the match, which means `$.`` gives the position of the `[`; the `>` modifier alters this to the prefix of the match's right separator, which gives the position of the matching `]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22 21 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
No doubt it is possible in Jelly in half this byte count :p ...
```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä
```
A monadic link accepting a list of characters which returns a list of lists of integers.
As a full program it accepts a string and prints a representation of said list.
**[Try it online!](https://tio.run/##y0rNyan8/z/vUdOawzOiH@5o1T201ffh7u7DLYcnHFuSCRQ2ODLtWNejhpmHW/7//68UDQKJxSmxicWxQDIlLTYtPS02GgiVAA "Jelly – Try It Online")**
### How?
```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä - Link: list of characters    e.g. "[f[o]o!]"
  Ø[                - list of characters = ['[', ']']
n€                  - not equal? for €ach              [[0,1],[1,1],[0,1],[1,1],[1,0],[1,1],[1,1],[1,0]]
                    -     ...relating to the characters:  [     f     [     o     ]     o     !     ]
    ḅ-              - convert from base -1             [1,0,1,0,-1,0,0,-1]
                    -     ...i.e.: 1 where '['; -1 where ']'; and 0 elsewhere
      µ             - start a new monadic chain with that as the argument, say V
                Ɗ   - last 3 links as a monad (function of V):
          ÐƤ        -   for post-fixes:
         Ä          -     cumulative sum               [[1,1,2,2,1,1,1,0],[0,1,1,0,0,0,-1],[1,1,0,0,0,-1],[0,-1,-1,-1,-2],[-1,-1,-1,-2],[0,0,-1],[0,-1],-1]
            i€0     -   1st index of 0 in €ach (or 0)  [8,1,3,1,0,1,1,0]
               Ė    -   enumerate                      [[1,8],[2,1],[3,3],[4,1],[5,0],[6,1],[7,1],[8,0]]
       M            - maximal indices of V             [1,3]
        ị           - index into                       [[1,8],[3,3]]
                 ’  - decrement                        [[0,7],[2,2]]
                  Ä - cumulative sum (vectorises)      [[0,7],[2,4]]
```
[Answer]
# SWI-Prolog 254 bytes
```
d([']'|T],I,[S|Z],M,R):-J is I+1,d(T,J,Z,[',','(',S,',',I,')'|M],R).
d(['['|T],I,S,M,R):-J is I+1,d(T,J,[I|S],M,R).
d([_|T],I,S,M,R):-J is I+1,d(T,J,S,M,R).
d(_,_,_,R,R).
m(X):-atom_chars(X,A),d(A,0,[],[']'],[_|R]),atomic_list_concat(['['|R],S),print(S).
```
Example:
```
?- m('!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]').
'[(49,50),(42,48),(8,41),(36,39),(20,33),(21,27)]'
true
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 87 bytes
```
f(char*Z){for(char*z=Z,*q=z;*z;*z++-93||printf("%d,%d;",*--q,z-1-Z))*z-91||(*q++=z-Z);}
```
[Try it online!](https://tio.run/##VU7BjoMgED1vv8KQmADCwbR7aI1fsTfpHIwUdGO1Ch5W7be7iG12HZjwmHnvzRRcF8WyKFyUeU8zMqm23/CYZox26ZjQ9UYRPx/n@dFXjVUYhZKFMkGMct6xkcc8I4SO/BzPM6ZdFKWjqyTPxd6M3eyM7cnk0Zft03te122BXbG@NetDopgk5mXvGAyFBrG1kbxnVs1jsMElCM21aQfrPpfgRfESxxyswejaIDf6cM@rBpPp8OF3QELkRioQIKzEgtifz5MOAyi1EAoGEEqI71KD0ErCSnRpQJcSVH86KnCWf06wHXgjFxhcEPKf5juwVwq/BuTG@YOborRfaUfaKzAQX3guvw "C (gcc) – Try It Online")
# Explanation
To keep track of opening bracket's string indices, the input string is overwritten and used as a stack.
```
f(char*Z){          // take mutable input string
 for(char*z=Z,*q=z; // copy pointer to current string index, current stack index
 *z;                // loop through the entire string
 *z++-93||          // if z == ']'
   printf("%d,%d;", // decrement stack pointer,
    *--q,z-1-Z))    //  write bracket pair position
  *z-91||           // if z == '['
   (*q++=z-Z);}     // write bracket position onto stack, increment stack pointer
```
[Try it online!](https://tio.run/##bZHdbqMwEIWvl6cYIaFiflRF7V60iKfYu7i@oGCDt8QmtlFb0j57djCkDdUOQjbjcw6fxnXe1vX5LOK6q0yyJyf4qttbcNULh8Poqueeg1TD6MA6I1UbgNBm8UzlPkuO5VTMhloP7zBoqRw34DTUozFcXVwY0fC37Kpb1S9LM4AEE34UBvZaD@A6o8e2w5UD@qThXxjJlKb5w93Hx8YlBUxQlnDDbgLsDKh1Ig6jJouaIsxmScNrww/fFCt0NushyfNjNuW7fE/IGgmvRjoOzwbF3MFQSYMeK53UCj3JlD/srik2GNRjxMkxTcsJQ4vPi@RH6hoIWuHwPFiG8/kv6dlx65YrwGGQk9/9caY8VH2v6xibPVfzQtIdKew6BFRkYWTDbD4oLpNZ7vYRIvuk9Ojw4xFWibegcnQ2Dp9UiPDBoZIqJqfgl2cIKa1sIxhl1DUxJe79930bAetaSgUbGRWU/u1aRlvRsFmIr2Vt1zBh7u8Ew8jvJLY87LLDihkWIdcyf8K2TuoxWGUxn@FfROuRNqKtI2bENz7P/wA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
=©ⱮØ[_/aÄ$+®ŻĠḊẎ_2s2
```
[Try it online!](https://tio.run/##y0rNyan8/9/20MpHG9cdnhEdr594uEVF@9C6o7uPLHi4o@vhrr54o2Kj/4fbj056uHPG///q0dGJxSlpsdGx0SUpGtGaJZWmJumqCrEZ6dHRabGlsdFp0dFZGemx0elpKbEghUBcHJuekRKbVmRinBarDgA "Jelly – Try It Online")
It has a side-effect on the register, hope it's allowed to be a function.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v1.4.5, 23 bytes
```
;Ë¥']?ApENo):D¥'[©NpE
A
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O8ulJ10/QXBFTm8pOkSlJ1upTnBFCkE=&input=LVEKIltbYXNkZl1bXVt0ZChbKXR5NTRnJSBdaGdbW2ZddV1bZltbamhnXVtnZmRdc2RmXXNkZnNdZ2hkXWZyNDNmXSI=)
### Unpacked & How it works
```
;UmDE{D==']?ApENo):D=='[&&NpE
A
;                              Use alternative set of initial variables
                               A = [] is used here
 UmDE{                         Map over each char of input string...
      D==']?                     If the char is closing bracket...
            ApENo)                 Push the current index and N.pop() to A
                  :D=='[&&       Otherwise, if the char is opening bracket...
                          NpE      Push the current index to N
A     Output A
```
The output is a flattened array of `[closing index, opening index]`. If the reversed order is not desired, adding `w` at the end does the job (+1 bytes).
[Answer]
## Common Lisp, 95 bytes
```
(lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
```
Long version
```
(defun par (string &aux stack)
  (dotimes (pos (length string))
    (case (char string pos)
      (#\[ (push pos stack))
      (#\] (print (list (pop stack) pos))))))
```
Tests
```
((lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
 "!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] ")
```
prints:
```
(21 27)
(20 33)
(36 39)
(8 41)
(42 48)
(49 50)
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~38~~ 37 bytes
```
{b@0N 2#,/=(|':+\-/a)b:&|/a:"[]"=\:x}
```
[Try it online!](https://tio.run/##NZDrbsIwDIX/7yms7tZqIBonvXpIe4K9gLFEEUrZmEAqTCoC9uqd20KiKJHlc77jbKe7etd1vjyvPuJPwMfJbB5eXsu3xXRWRavy5TKryoAlmC/K9tod9s2xPLcf7@31QR9P3Bf4JH/9DU3poaXlfkvh0ldfP9TSiZpItJcD5uqw9sLCx3XI0fGUuPoZZFMze/kV9szfm1q49mvpG/UcpN6sxTfOegkojCFFMpBSBjkVkKRkLCASJmBjwhQwJ2sgQbIWXEbWgdVKAc5GMkaQccv9pSuUfkXRACjUX@XgKLlxTAyoIAMGe5xxZBIwWskAEzI5oFYKQEuonXgDDd4yhjaEYMlB1nveg/DwHVIddE7RaX09fM2oQKMxTKY6xSnTqDonxIHilHunBDRR/5tlKNEo11igE3f/ "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`"[]"=\:x` two boolean lists for the occurrences of `"["` and `"]"`
`a:` assign to `a`
`|/` boolean "or" of the two lists
`&` where (at which indices) are the brackets?
`b:` assign to `b`
`-/` a list with 1 for `"["`, -1 for `"]"`, and 0 everywhere else
`+\` partial sums
`|':` pairwise maxima (each element max'ed with the previous one, the initial element remains the same)
This represents bracket depth for each character.
We index it with `b` (juxtaposition is indexing) and get bracket depth only for the brackets.
`=` "group by" - a dictionary mapping depths to the indices at which they occur
`,/` concatenate the values in the dictionary, ignoring the keys
`0N 2#` reshape to a 2-column matrix (list of lists)
`b@` index `b` with each element of the matrix
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
ＦＬθ≡§θι[⊞υι]«Ｉ⊟υ,Ｉι⸿
```
[Try it online!](https://tio.run/##VcpPC4IwHMbxs76KJQg/wU4lQZ2iU9DB@1ow9scpw@U2Mwhf@1IpqOPzeb5MUcsM1SFIYxFcRFt5BV2WITfUnikER39uuXhCl6N64lccMeoESnCyR2XvFPTzcfgymXhqotLWrYcTdR5Kc4c@y@bmw0me/Kwlqv/@q12CMR5DWN22heOSYyW0NmgwVnOMeSN7T9J0U@yIs7iRxBHsrOcVwSQO64d@Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
ＦＬθ
```
Loop over the implicit range of the length of the input string.
```
≡§θι
```
Switch on the current character.
```
[⊞υι
```
If it's a `[` then push the current index to the predefined array variable.
```
]«Ｉ⊟υ,Ｉι⸿
```
If it's a `]` then pop the latest index from the array variable and print it and the current index separated by a comma and start a new line. Alternate output formats, if acceptable, would save some bytes: `]Ｉ⟦⊟υιω` saves 2 bytes but prints each index on a separate line, double-spacing the pairs of indexes; `]Ｉ⟦⊟υι` simply prints the indexes on separate lines, making it hard to distinguish them.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 25 bytes
```
0q{"[]"#"_ \p_p "S/=~)}/;
```
Surprisingly competitive - loses only to Japt and Jelly [**Edit**: and Charcoal and Stax :(]
[Try it online!](https://tio.run/##Fco7CoQwFAXQrYQMgqkURitxFVNeLyKG90JA8DfFILr1OBanO2McppTK5bCgfdnedHM/G/sp2sudRZMSMGxeCGL3Odz@qyvNDIMCwi8hQAxKqHg@8W@jBk9Zq7fwBg "CJam – Try It Online")
## Explanation
```
0                          Push 0.
 q                         Push the input.
  {                   }/   For each character in the input:
   "[]"#                     Find index of this character in the string "[]" (or -1 if not found).
                   =         Use this index to choose
        "       "S/            one of the following snippets
                    ~          and execute it:
         _                       If it was 0 ('['), duplicate the number on the stack.
           \p_p                  If it was 1 (']'), print the current number and the one under it.
                                 If it was -1, do nothing.
                     )       Increment the number on top of the stack.
                        ;  Delete the number.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 109 bytes
```
def a(s,r=[],i=0):
 o=[]
 while i<len(s):exec["r+=[i]","o+=[(r.pop(),i)]",'']['[]'.find(s[i])];i+=1
 return o
```
[Try it online!](https://tio.run/##NY3NasQwDITvfgoRCLbYEPqzvaTNk2h1CHWceEltI3tp9@lTp0tHCGaGDybdyxrDy77b2cFkcicjcefHJxwUxOoVfK9@m8F/bHMwGYf5Z/6kRk4jeW66JlZjpE8xGew81kprJk2se@eDNbliyO/@ND4rkLncJEDc/VeKUiDfs3JRYPOhLoQj97lYH4YkPpRmMq0gjJcA0ErTmoOrgPhk9CVo7Ka/CnEnmrJ1TEzFGsJyfzsvLfC6EDm@MTmi67owLc7yAdbPvKyWnZxfHSsifhz/uyrDVYjqkZl/AQ "Python 2 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~28~~ 26 bytes
```
{I#.e,t+lhfSI/LT`Y+._>Qk\]
```
[Test suite.](https://pyth.herokuapp.com/?code=%7BI%23.e%2Ct%2BlhfSI%2FLT%60Y%2B._%3EQk%5C%5D&input=%22%21%5E45sdfd%5Bhello+world%5B%5Bdjfut%5D%25%25357%5Dsr%5Bjf%5Ds%5D%5Bsrtdg%5D%5B%5D%22&test_suite=1&test_suite_input=%22%5B%5Basdf%5D%5B%5D%5Btd%28%5B%29ty54g%25+%5Dhg%5B%5Bf%5Du%5D%5Bf%5B%5Bjhg%5D%5Bgfd%5Dsdf%5Dsdfs%5Dghd%5Dfr43f%5D%22%0A%22%5B%5B%5D%5B%5D%5B%5D%5B%5D%5D%5B%5B%5D%5B%5D%5B%5D%5B%5B%5B%5B%28%5D%5D%5D%5D%29%29%22%0A%22%5B%5D%5B%5D%5B%5B%5D%5D%22%0A%22%5B%5B%5B%5B%5Basd%5Das%5Dsd%5Ddf%5Dfgf%5D%5B%5D%5B%5D%22%0A%22%5B%5D%22%0A%22%5B%5B%28%5D%29%5D%22&debug=0)
~~At the moment it's longer than Mnemonic's approach~~, but I feel like I can golf this down a little and this fortunately also doesn't use Pythonically-imperative structures like `V`. The initial version was 36 bytes and also had numerous bugs.
### How it works
```
{I#.e,t+lhfSI/LT`Y+._>Qk\] – Full program. Takes a quoted string Q from STDIN.
   .e                      – Enumerated map. k = iteration index, b = current element.
                     >Qk   – Get the elements of Q at indices greater than k.
                   ._      – Generates all the prefixes of this.
                  +     \] – And append an "]" (for handling some edge-cases).
          f                – Filter over this list, with T = current element.
              L `Y             – For each character in str([]), "[]"...
             / T               – ... Count the occurrences of it in T.
           SI                  – And check if the values are sorted increasingly.
         h                 – Head. Retrieve the first element.
       +l                  – Get the length of this + k.
      t                    – Decrement (by 1).
     ,                     – And pair this value with k. Returns [i, k] where i is
                             the index of the corresponding ] and k is that of [.
  #                        – Filter this list by:
{I                             – The pair is invariant over deduplicating.
```
[Answer]
# Perl 5, 53 bytes
```
say"$-[0] ".($+[0]-1)while s/\[[^][]*\]/1x length$&/e
```
Run as `perl -nE '<above code snippet>'`. Takes input through stdin.
As usual, the optimal Perl solution to the problem is a regular expression. We attempt to match any pair of brackets which does not contain any pairs within it using a rather silly-looking character class (`s/\[[^][]*\]/.../`). If the match is successful, we replace the matched text with the digit `1` over and over again so that we don't accidentally match those brackets again, and we print out the indices of the match. Rinse and repeat.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é√p(l▓1½\á²ë(
```
[Run and debug it](https://staxlang.xyz/#p=82fb70286cb231ab5ca0fd8928&i=%22[[asdf][][td%28[%29ty54g%25+]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]%22%0A%22[[][][][]][[][][][[[[%28]]]]]%29%29%22%0A%22[][][[]]%22%0A%22[[[[[asd]as]sd]df]fgf][][]%22%0A%22[]%22%0A%22[[%28]%29]%22&a=1&m=2)
It uses the input stack to track open brace pairs. Here's the program unpacked, ungolfed, and commented.
```
F       iterate over input characters
 .][I   get the index of the character in the string "[]", or -1
 ^|cv   skip the rest of this iteration if index was -1
 i~     push the current iteration index to the input stack
 C      skip the rest of this iteration if index was 0
 \      form a pair with the top two items from the input stack
 JP     join with space, and print
```
[Run this one](https://staxlang.xyz/#p=82fb70286cb231ab5ca0fd8928&i=%22[[asdf][][td%28[%29ty54g%25+]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]%22%0A%22[[][][][]][[][][][[[[%28]]]]]%29%29%22%0A%22[][][[]]%22%0A%22[[[[[asd]as]sd]df]fgf][][]%22%0A%22[]%22%0A%22[[%28]%29]%22&a=1&m=2)
]


[Question]
      [
**This question already has answers here**:

[Non-Unique/Duplicate Elements](/questions/60610/non-unique-duplicate-elements)
 (60 answers)

Closed 5 years ago.
So, I have an array
```
['a', 42, 'b', 42, 'a']
```
I want to alert users to the fact that 42 and 'a' appear in it twice.
```
some_function(['a', 42, 'b', 42, 'a'])
```
should return
```
['a', 42]
```
---
Write some code to extract the duplicates from an array.
* It should accept an array as input.
* The array can have multiple types of object.
* Duplication should be defined as per the language's standard equality function (examples are from ruby).
* It outputs an array of the duplicated items.
* The order of the returned items is irrelevant.
* Duplicates should only appear in the returned array once.
* Golf rules, do it in the smallest number of bytes.
Test cases
```
[1,2,3] => []
[1,2,3,2,1] => [1,2]
[1.0, 2, 2.0, 1.0] => [1, 2] or [1.0, 2.0] or [1, 2.0] or [1.0, 2]
[1, '1', '1.0'] => []
[nil, nil, false, false, true, true] => [nil, false, true]
```

[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
ọ{tℕ₂&h}ˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3uqSRy1THzU1qWXUnl70/3@0oY6RjrGOUklqcYkSkGkIY0Ko2P9RAA "Brachylog – Try It Online")
### Explanation
```
ọ           Occurrences
 {     }ˢ   Select:
     &h       The elements…
  tℕ₂         …which occur at least 2 times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
{γʒg≠}€н
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@tzmU5PSH3UuqH3UtObC3v//ow11jHSMgdgwFgA "05AB1E – Try It Online")
**Explanation**
```
{γ       # Sort input and split into chunks of identical elements
  ʒg≠}   # Keeps chunks of length != 1
      €н # Map with the first element of each chunk
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
{.-Q{
```
[Try it here!](https://pyth.herokuapp.com/?code=%7B.-Q%7B&input=%5B1%2C+2%2C+3%2C+2%2C+1%5D&debug=0)
### How it works?
```
{.-Q{ – Full program.
    { – Deduplicate.
 .-Q  – And apply bagwise subtraction between the input Q and the above.
{     – Deduplicate the result.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~39~~ 38 bytes
```
lambda l:{v for v in l if~-l.count(v)}
```
[Try it online!](https://tio.run/##bY47C8IwFIV3f8UBh7QQSxudhDo6Orlph1QNFmJSalsQ0b8e01ds0eGe@/jO5d78UV61YkbERyP5LT1zyPWzhtAFamQKEpl4L2Rw0pUqvdp/mbzIVAnhHQgnFCtGQdKh4CTx50C8wUCT2cwtRJTRpTP8EBuRo3YyMQQhhb3AmmybkQ8sgf22t1jUdeO6JdN7IBFpJAjJ3492Wl0oOt1yef@mfVH16hYntpaYDw "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda l:[*map(l.remove,{*l})]and{*l}
```
[Try it online!](https://tio.run/##bU/LCsIwELz3KxY8pC2htKknoR49evJWc0hpi0IeJVZBxG@P6cs0KCGzs5lZJts9@4uSuWmLs@FMVDUDvitjwbqQJ7oR6tHgV8zfEWWyHojp9FX2YRuWiCEMW4IBVQthiEbRBqDYwyLTIPhOZJjg3Dl@JHszJ9snz5GkGGwIGapt1kYgFJSG2WO1qVvzUfETAWVogCRF/z91VLLBMOGB8ZsrJ32f0U16vlHy0taH2NW8Pc0H "Python 3 – Try It Online")
[Answer]
# Javascript ES6, 48 bytes
```
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))]
```
Test cases
```
f=
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))];
tests=[
    [1,2,3],
    [1,2,3,2,1],
    [1.0, 2, 2.0, 1.0],
    [1, '1', '1.0'],
    [undefined, undefined, false, false, true, true],
    [1,2,1,1,1,2,1,2,2,1,1]
]
console.log(tests.map(b=>f(b)))
```
[Answer]
# [R], 58 bytes
```
function(x)x[duplicated(x)]
```
(My original code was nonsense.)
This works with an array input (in R an "atomic vector") but all the elements have to have the same type, or will be coerced to the most general type.
This also works with a list input (the only way in R an "array"-ish object can have elements of different types) which is what the challenge seems to want. The list elements can be other lists, atomic vectors, matrices, data frames - anything, really.
But then the "equality" function used by `duplicated` is fairly strict and won't give the same answers as the challenge test cases indicate, which is a flaw in the challenge specs and not this answer.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
"GX@&)m?6Mvu
```
[Try it online!](https://tio.run/##y00syfn/X8k9wkFNM9fezLes9P//akMdBXVDdRChZ6BeCwA "MATL – Try It Online")
*Thanks to Luis Mendo for saving a byte!*
using `m` is the only way I could use mixed-type equality checking. Takes input as a row cell array.
```
		% (implicit input x)
"		% for loop:
GX@&)		% push input and index, then get x(i) and x(-i),
                % where x(-i) means "x excluding element at index i"
    m		% ismember -- true if x(i) is in x(-i)
     ?		% if true
      6M	% get x(i)
	v	% concatenate with prior results
	 u	% and take unique values
		% implicit end of if
		% implicit end of for loop
		% implicit end of program, output results as cell array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
œ-QQ
```
[Try it online!](https://tio.run/##y0rNyan8///oZN3AwP///0cb6hnoKBgBEYgGcmIB "Jelly – Try It Online")
The last test case (`[None, None, False, False, True, True]`) isn't possible in Jelly.
[Answer]
# [PHP](https://php.net/), 75 bytes
```
function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUEjVUkjSri1JLSouAnKKixMr40rzMwtJUDQgnJTMtLT6xuDg/GahQB0UBUKOmpnXt/7LEoviU0twCjUSNaPVEdR0FEyMdBfUkGCNRPVZTk4vL3u4/AA "PHP – Try It Online")
[Answer]
# [Javascript (ES6)](https://developer.mozilla.org/bm/docs/Web/JavaScript), 51 bytes
```
a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]
```
[run on tio](https://tio.run/##NYpBCsMgEAC/4s2VmoWWXjef6FFyWNO1WESLinm@TQ@9DMMwbx7c9ho/ffHsJS25PGUGmkyrQ8Qsh3pIB8ZWageDIaYuFWDYaGgdRMQuXq6bMdvcS24lCabyggBOs7bqfrNK@7/8yonznl8).
Try it:
```
a=a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]
console.log(a([1,2,3]));
console.log(a([1,2,3,2,1]));
console.log(a([1.0, 2, 2.0, 1.0]));
console.log(a([1, '1', '1.0']));
console.log(a([null, null, false, false, true, true]));
console.log(a([1,1,1,3,2,3,2,3,4]));
```
[Answer]
# Powershell, ~~38~~ 32 bytes
```
($args|group|?{$_.count-1}).Name
```
[Try it online](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9uCa9KL@0oMa@WiVeLzm/NK9E17BWU88vMTf1////hv@N/hsDsSEA), thanks [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)
using:
1. save the code to a file `get-duplicates.ps1`
2. run `.\get-duplicates.ps1 'a' 42 'b' 42 'a' 42`
Known issues: Powershell supress `$null` value. Result of
```
 .\get-duplicates.ps1 $null $null $false $false $true $true
```
is `False, True` without `null`.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 77 bytes
```
l->{java.util.Set.copyOf(l).forEach(l::remove);return l.stream().distinct();}
```
[Try it online!](https://tio.run/##bZBdb4IwFIbv/RUnJCbtUpvp7kBJzLJdbfGCS@NFxeLKCiXtwYUYfjsroJtmS4DD@ej7vD25OIlZfvjsVFEZi5D7nNeoNH@IJn9qWV2mqEz5b9OhlaLoW6kWzsG7UCWcJwBVvdcqBYcCfTgZdYDC90iCVpXH7Q6EPTo6jAK8XhDLN@WQJYNmDNmq07P4/AtLJPLUVM0mI5ryzNgXkX4QHYZWFuYkaWQl1raEqy1C@cELKi9OaNR20QDb7HOZ4nbnPaB06GB1cQFwnrMFe2rZXerf@U2JPzJY@KePPrkdDtYBG7@Ldqi2I9E7JVfqwAxHMv0B9/dejiMxaO@olF@wtlY0Qycmw7/jwvU56U9TGl0OJ41DWXBTI6/8cjEjwdSFMHXTMmD3Sn5vDDIuqko3/Q5To7VnkucxGus4mmGQXvX7m7STtvsG "Java (JDK 10) – Try It Online")
[Answer]
# [Crystal](https://crystal-lang.org), 42 bytes
```
def f(a)a.reject{|x|a.count(x)<2}.uniq
end
```
[Try it online!](https://tio.run/##bY1BDoMgEEX3nmJiN5gQorit3fcMhgVRSG0NtoiNRjy7BbSNiybwh//fzFDpqTe8XddaSJCIJ5xocReVme1oOam6QRk0Jme6kEE1r0ioep2jMsMU5wyKC5QMOglXZXKK99zdbGPOMp@SFAN1x1dnvhAchVOnYe/wJLjjOxDmV0OcxV5IGv/5WjUthiCSt734FaOHXbehY0tIo4UIXt1m@xATfvPWPuGJJHIuSYrCBcv6AQ "Crystal – Try It Online")
Sometimes, when you can't get the desired results, the problem can be solved... by running your code in a different language.
Initially, I tried solving this in Ruby, but ironically, despite the OP's statement that all test cases correspond to Ruby comparison rules, the above code when run in Ruby actually fails for the third test case, as both `uniq` and array intersection operator use stricter equality checks. However, it passes all tests in Crystal (which shares most of its syntax with Ruby) at the expense of having to declare it as a defined function (`->` proc would be longer in Crystal).
As a bonus, here is the golfier Ruby-only version of the code (doesn't pass test 3):
### [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->a{a.reject{|x|a.count(x)<2}|[]}
```
[Try it online!](https://tio.run/##TY3NDoMgEITvfYpNelATStReiy9COFCD6Y9RQ7XRAM9OF7StCczyzUwWPV0X3zB/qqSRVKuHqkdjZytp3U/dmM7ZpXSWC@fNgRekJGcBrAIuyIZ4i9VCjC7NCZR4wkT4hoApHHsNWyMkkfbvmIiwGpIiCULz5P9jd28JRGlk@1K/Mepp07W7r0T34KiS9c3Yp1rIW7Z2gCFtOJLIGEPD@Q8 "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-h`, 7 bytes
```
â £kX â
```
[Try it online!](https://tio.run/##y0osKPn///AihUOLsyMUDi/6/z/aUEcBiIzApDGQEcvFpZsBAA "Japt – Try It Online")
## Explanation:
```
â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
:uDu
```
[Try it online!](https://tio.run/##S0/MTPz/36rUpfR/6qO2if@jDRWMFIyB2DAWAA "Gaia – Try It Online")
`:` duplicates the input, `u` uniquifies it, `D` retrieves the multiset difference between the two and `u` uniquifies the result.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
uṠ-u
```
[Try it online!](https://tio.run/##yygtzv7/v/ThzgW6pf///4821DHUMQJCYx2jWAA "Husk – Try It Online")
**Explanation**
```
     -- input, e.g. [2,1,1,3,2,2]
   u -- remove duplicates: [2,1,3]
 Ṡ-  -- subtract this from original list: [2,1,1,3,2,2] - [2,1,3] = [1,2,2]
u    -- remove duplicates: [1,2]
```
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 33 bytes
```
->a:Set@Filter[->e:a.count@e>1;a]
```
[Try it online!](https://tio.run/##K8ioLM5MTvyfZhvzX9cu0So4tcTBLTOnJLUoWtcu1SpRLzm/NK/EIdXO0Dox9n9AUSaQkxZdbWhtZG0MxIa1sf8B "Physica – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
nub.((\\)<*>nub)
import Data.List
```
[Try it online!](https://tio.run/##y0gszk7NyfmvnJKalpmXqpCmEPM/rzRJT0MjJkbTRssOyNbkyswtyC8qUXBJLEnU88ksLvmfm5iZp2CrUFCUmVeioKKgkaapEG2oY6RjqGMMJI1i//9LTstJTC/@rxvhHBAAAA "Haskell – Try It Online") Port of my [Husk answer](https://codegolf.stackexchange.com/a/166298/56433).
The point-free version given above is equivalent to `f x=nub$x\\nub x` which is one byte longer.
---
### [Haskell](https://www.haskell.org/), 50 bytes
```
([]#)
a#(x:r)=([x|any(==x)r,all(/=x)a]++a)#r
a#_=a
```
[Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPNfIzpWWZMrUVmjwqpI01YjuqImMa9Sw9a2QrNIJzEnR0MfyEqM1dZO1FQuAiqLt038n5uYmQfUW1CUmVeioKKQphBtqGOkY6hjDCSNYv//S07LSUwv/q8b4RwQAAA "Haskell – Try It Online") Alternative without imports.
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 32 bytes
```
l=>set(v for v:l if~-l.count(v))
```
[Try it online!](https://tio.run/##KyjKL8nP@59mq/E/x9auOLVEo0whLb9IocwqRyEzrU43Ry85vzQPKKqp@V@Tq6AoE8hO04g21FEw0lEwjtXEFAOThqgyegZgUSMQDeSga1M3VAcRegbqKDJ@@XmpOgoQ0i0xpxhBhRSVQkmghv8A "Proton – Try It Online")
Port of TFeld's Python answer. Could be shorter but `{...}` apparently doesn't work for setcomps.
[Answer]
# [Red](http://www.red-lang.org), 46 bytes
```
func[b][foreach c unique b[alter b c]unique b]
```
Doesn't work for numbers in different representation as float or string.
[Try it online!](https://tio.run/##XYlBDsIwDATvfcUqP2jhxDO4Wj44qS0qVS6Y5P0BURUhDjurnQ2d@1Vn4sEu3ZoXyky2hUq5oaD58miKTLJWDWQUPhT3eyxeYaAkCecJKe8liYfvN2LC6X@/M/4431zxgcn6PFij7eD@Ag "Red – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
═H+U(
```
[Run and debug it](https://staxlang.xyz/#p=cd482b5528&i=[%22a%22,+42,+%22b%22,+42,+%22a%22]&a=1)
Explanation:
```
cu|-uJ Full program, unpacked
cu     Copy and make unique
  |-   Remove each element once
    u  Make unique again
     J Join by space. 'm' would be equally long, but as F has a lower charcode, it can be packed better.
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 22 bytes
```
Lmsl`(.+)(?=.+^\1$)
D`
```
[Try it online!](https://tio.run/##K0otycxLNPz/3ye3OCdBQ09bU8PeVk87LsZQRZPLJeH/f2MuIy5DLhBpDAA "Retina – Try It Online") Explanation:
```
Lmsl`(.+)(?=.+^\1$)
```
List duplicated lines. The `m` modifier allows the `^` and `$` to match the start and end of a line in the lookahead. The `s` modifier allows us to look ahead past newlines using just `.+`. The `l` modifier automatically anchors the match to whole lines. I can't use the `p` flag though as the match could be more than one line at once, however the next stage will deal with that.
```
D`
```
Deduplicate that list.
]


[Question]
      [
Given a nonempty array of positive integers, "increment" it once as follows:
* If all the array elements are equal, append a `1` to the end of the array. For example:
```
[1] -> [1, 1]
[2] -> [2, 1]
[1, 1] -> [1, 1, 1]
[3, 3, 3, 3, 3] -> [3, 3, 3, 3, 3, 1]
```
* Else, increment the first element in the array that is the array's minimum value. For example:
```
[1, 2] -> [2, 2]
[2, 1] -> [2, 2]
[3, 1, 1] -> [3, 2, 1] -> [3, 2, 2] -> [3, 3, 2] -> [3, 3, 3]
[3, 4, 9, 3] -> [4, 4, 9, 3] -> [4, 4, 9, 4] -> [5, 4, 9, 4] -> [5, 5, 9, 4] -> ...
```
(Each `->` represents one increment, which is all your program needs to do.)
Output the resulting incremented array.
**The shortest code in bytes wins.**

[Answer]
# **MATLAB, ~~69~~ 67 bytes**
```
function a=f(a);if~range(a)a=[a 1];else[~,j]=min(a);a(j)=a(j)+1;end
```
`range(a)` is non-zero if not all elements are equal, and `[~,j]=min(a)` assigns the index of the minimum value in a to j, defaulting to the first value it finds. Input is a row vector. Saved 2 bytes by reversing the if/else logic to get rid of some semicolons (`else[~,j]` is legal, but `elsea=[a 1]` is not).
[Answer]
**Clojure, ~~112~~ 100 bytes**
Unfortunately `min-key` returns the last index of the smallest index, not the first one. This works for integer inputs and shorter arrays than 10^9 elements ;)
Edit: Defining an anonymous function, using `(apply = a)` instead of `(= 1(count(set a)))`.
```
(fn[a](if(apply = a)(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))
```
Original:
```
(defn f[a](if(= 1(count(set a)))(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))
```
A less hacky 134-byte solution reverses the vector before updating it and then reverse it back again:
```
(defn f[a](if(= 1(count(set a)))(conj a 1)(let[r #(vec(reverse %))a(r a)](r(update a(apply min-key #(nth a %)(range(count a)))inc)))))
```
[Answer]
# MATLAB, ~~66~~ 53 bytes
```
if(range(a))[~,b]=min(a);a(b)=a(b)+1;else;a=[a 1];end
```
Output:
Initialize:
```
a = [3 2]
```
Successive runs:
```
[3 2] -> [3 3] -> [3 3 1] -> [3 3 2] -> [3 3 3] -> [3 3 3 1] ...
```
[Answer]
# SmileBASIC 3, 101 bytes
Defines a statement function `I A` where `A` is our integer array of numbers. Output is achieved by modifying the input (as arrays are references.)
```
DEF I A
M=MIN(A)IF M==MAX(A)THEN PUSH A,1RETURN
FOR C=0TO LEN(A)IF M==A[C]THEN INC A[C]BREAK
NEXT
END
```
[Answer]
# SmileBASIC, 77 bytes
```
DEF I A
IF MIN(A)==MAX(A)THEN PUSH A,0
WHILE A[I]>MAX(A)I=I+1WEND
INC A[I]END
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 24 bytes
**Solution:**
```
{(x[x?&/x]+:1;x,1)1=#?x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWqMiusJeTb8iVtvK0LpCx1DT0FbZvqL2f5q6ho6htY6RtaGCobWxAhQCeUbWRmARiLiJgqWCseZ/AA "K (oK) – Try It Online")
**Explanation:**
Nothing too fancy, potentially golfable further:
```
{(x[x?&/x]+:1;x,1)1=#?x} / the solution
{                      } / anonymous lambda taking implicit x argument
                     ?x  / get distinct values in x
                    #    / count length
                  1=     / is it 1?
 (           ;   )       / two item list which is index into
              x,1        / append 1 to input
  x[     ]+:1            / modify x in-place (add 1) at index given in []
      &/x                / minimum of x
    x?                   / lookup index (returns first one)
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 10 bytes
```
≈[1J|g₌ḟ›Ȧ  # main program
```
```
≈           # all elements in input are equal
 [1J|g₌ḟ›Ȧ  # main if statement
  1J        # if true, append 1 to input
     g₌ḟ›Ȧ  # if false...
     g      # get the minimum
      ₌ḟ›   # push the index of the min and the increment of the min
         Ȧ  # set that index to the increment
            # implicit output
```
I came up with this independently but surprisingly it was pretty similar in structure to @AaronMiller's answer.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%89%88%5B1J%7Cg%E2%82%8C%E1%B8%9F%E2%80%BA%C8%A6&inputs=%5B5%2C%202%2C%203%5D&header=&footer=)
[Answer]
# JavaScript, 55 bytes
```
a=>a.every(e=>e==a[0])?a.push(1):a.fill(Math.max(...a))
```
Modifies the array passed to it, otherwise, it's 3 bytes longer:
```
a=>a.every(e=>e==a[0])?a.push(1)&&a:a.fill(Math.max(...a))
```
[Try it Online!](https://tio.run/##RY9BT8MwDIXPza@wdiGRsoxuMDGklAPiggQc4Fb1YBVnK@qSKskGFeK3lzRCQu/gz7b8nvyBZwyt74a4tO6dJqMn1BUqOpMfOemKtMb6shF3qIZTOPBS3KIyXd/zJ4wHdcQvrpRCIabW2RDhjUK8x0ABNNSsqMtGQirrRs6NXMtNpk2iMtON3Mpdpit5nbT9m25mZd7JpIY1jBnneUwB4Mx/kIBvVsTjkAIfX1@e1YA@EM8You/svjNjvhICVit4sOHkCbp4EQDB0ieg9zhKsC6mgSdDnmxLrDA8uQpWzI@5nlTv9tlHLpbVQubdz/QL)
## Explanation
```
a=>a.every          // Check that every element "e"...
  (e=>e==a[0])      // ...is equal to the first element.
    ?a.push(1)      // If it's the case push 1 at the end.
      :a.fill       // Else fill the entire array...
        (Math.max   // ...with the biggest...
          (...a))   // ...entry of the array.
```
### Some notable parts
* Checking the first element of the array is valid because all of the elements needs to be the same anyways
* If the array have different elements, it will end up being an array filled with the largest number anyways, so let's do directly that
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~76~~ 60 bytes
```
$x,$y=($a=$args)|sort -u
$a[$a.IndexOf(+$x)]+=!!$y
$a+,1*!$y
```
[Try it online!](https://tio.run/##dZHfb4IwEMff@1ecpBswyhIrPuyBBbNkiU8uY2/GLBXrfgTFUchw6t/OziIgLmuapv1@7r53zW2Sb5mqdxnHJV2CD7uSFoxufYsKn4r0Tdl7laQZuDmhYkrF7Xi9kMVkaTm0sGeO3@vRLRKH9W/wVh4IIYFFmBVYfZsBngz6tq0FrgXeCprVQa08YNBuzTtKJ7/x5HWR2vNMG5zsT1a8U4p3Ce8Qflaed9o7J4OWeAzu6q699llx7x/uXXJP8@ElH/7hw4bbsIcr2BHAhXNLxZYBlcVGRplc4Fzpa4VSqfI4Q@Eaxx3oQA2mT@FDrrJkNZl/Ys4sqKyOK8yjSCqFOcYp3QBXfuGr9jea2NHRUEdq6xaY43VkIjDde7MRn@tmGmONDuSAv3lM0pXI3BcxjyW4ozxLwo8fWf4C "PowerShell – Try It Online")
[Answer]
# [Uiua](https://uiua.org), 19 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
(⍜⊡'+1⊢⍏.|⊂∶1)≍↻1..
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgKOKNnOKKoScrMeKKouKNjy584oqC4oi2MSniiY3ihrsxLi4KCmYgWzFdCmYgWzJdCmYgWzEgMV0KZiBbMyAzIDMgMyAzXQpmIFsxIDJdCmYgWzIgMV0KZiBbMyAxIDFdCmYgWzMgNCA5IDNdCg==)
```
(⍜⊡'+1⊢⍏.|⊂∶1)≍↻1..
                  .  # duplicate
              ≍↻1.   # are all elements equal?
(        |   )       # run the left part if not, or right part if so
          ⊂∶1        # append 1 to end
        .            # duplicate
      ⊢⍏             # index of minimum element
 ⍜⊡'+1               # increment value at that index
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
```
If[Equal@@#,Append@1,1+#&~MapAt~#&@@Ordering@#]@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMt2rWwNDHHwUFZx7GgIDUvxcFQx1BbWa3ON7HAsaROWc3Bwb8oJbUoMy/dQTnWQVntfwCQXRKtrGuXBhRQqwtOTsyrq@aqNqzV4ao2AhFAA0CUsQ4UQsTAUkYwKbgaEx1LoAqu2v8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Uiua](https://uiua.org), 14 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⬚0+⍘⊚?⧻⊢≍,⊃⍖⍏.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4qyaMCvijZjiipriipfDty_ihqXiiaAsLC_ihqcuLgoKZiDihpAg4qyaMCvijZjiipriiqLijY8u4oqC4oi24oqa4omN4oa7MS4uCmYg4oaQIOKsmjAr4o2Y4oqa4oalw5fiioPiioPiiY3ip7viiqLiioPijY_ijZYuCmYg4oaQIOKsmjAr4o2Y4oqaP-KnuyfiiqLijY_iiY3ihrsxLi4uCmYg4oaQIOKsmjAr4o2Y4oqaP-Knu-KKouKJjSziioPijZbijY8uCgpmLmYuZi5mLmYgNF8zXzlfMwpmIDNfM18zXzNfMwo=)
Finds the 0-based index to increment (or the length if the elements are all equal), and adds 1 at that index. The `⍏` (rise; the indices in the array that would put the values in sorted order) is reused three times:
* "all equal" test can be done with "rise matches fall"
* "the first index of minimum element" is "first of rise"
* "the length of the array" is the same as "the length of rise"
```
⬚0+⍘⊚?⧻⊢≍,⊃⍖⍏.    input: an array of positive integers A
            ⊃⍖⍏.   push fall(A), rise(A), A
          ≍,         keep rise(A) and evaluate "rise(A) == fall(A)"
      ?⧻⊢            if so, call length; otherwise call first on rise(A)
    ⍘⊚              inverse where; create an array B so that B[i] == count of i
                     (3 -> [0, 0, 0, 1])
⬚0+                  elementwise add the result to A, padding with zeros if needed
```
[Answer]
# Pyth, 16 bytes
```
?tl{QXxQhSQQ1+Q1
```
A program that takes input of a list and prints the result.
[Test suite](https://pyth.herokuapp.com/?code=%3Ftl%7BQXxQhSQQ1%2BQ1&test_suite=1&test_suite_input=%5B1%5D%0A%5B2%5D%0A%5B1%2C+1%5D%0A%5B3%2C+3%2C+3%2C+3%2C+3%5D%0A%5B1%2C+2%5D%0A%5B2%2C+1%5D%0A%5B3%2C+1%2C+1%5D%0A%5B3%2C+4%2C+9%2C+3%5D&debug=0)
**How it works**
```
?tl{QXxQhSQQ1+Q1  Program. Input: Q
?                 If:
  l                The length
   {Q              of Q deduplicated
 t                 - 1
                   is non-zero:
     X     Q1       Increment in Q at index:
      xQ             Index in Q of
        h            the first element
         SQ          of Q sorted (minimum)
                  else:
             +     Append
               1   1
              Q    to Q
                   Implicitly print
```
[Answer]
# Haskell, 93 bytes
`f z|and$(==)<$>z<*>z=z++[1]|1>0=z#minimum z where(x:z)#m|x==m=x+1:z;(x:z)#m|1>0=x:z#m;[]#_=[]`
**Ungolfed:**
```
incrementArray :: [Int] -> [Int]
incrementArray xs | and [x == y | x <- xs, y <- xs] = xs ++ [1]
                  | otherwise = g xs (minimum xs)
     where g (x:xs) m | x == m = (x + 1):xs
           g (x:xs) m | otherwise = x:g xs m
           g [] _ = []
```
Initial attempt, will try to come up with something more sophisticated later.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 44 bytes
```
@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1
```
This is not what I had in mind when I made this language... It's literally worse than Perl in terms of readability!
Usage:
```
(@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1])[3 4 9 3]
```
# Explanation
More readable:
```
@[
  dp 1 unq #0
    ? set #[
            get 0 (iO f\ min #0) #0
            + 1 f
           ] #0
    ? con #0 1
 ]
```
Basically checks if dropping 1 item from the unique subset of the argument makes the list empty. If not, then we increment the minimum of the array. Otherwise, we simply concatenate 1 to the argument.
[Answer]
## Kotlin, 75 bytes
```
fun a(s:MutableList<Int>){if(s.toSet().size<2)s+=0;s[s.indexOf(s.min())]++}
```
Modifies the function argument.
Damn you strong typing! `:MutableList<Int>` accounts for 17 bytes alone. I don't think there is a solution where the type can be inferred, unfortunately.
[Answer]
# jq, 44 characters
```
if unique[1]then.[index(min)]+=1else.+[1]end
```
Sample run (`-c` (`--compact-output`) option used only here for readability):
```
bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,1,1]'
[3,2,1]
bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,2,1]'
[3,2,2]
bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,2,2]'
[3,3,2]
bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,3,2]'
[3,3,3]
bash-4.3$ jq -c 'if unique[1]then.[index(min)]+=1else.+[1]end' <<< '[3,3,3]'
[3,3,3,1]
```
On-line test:
* [[3,3,3,3,3]](https://jqplay.org/jq?q=if%20unique%5B1%5Dthen.%5Bindex(min)%5D%2b=1else.%2b%5B1%5Dend&j=%5B3,3,3,3,3%5D)
* [[3,4,9,3]](https://jqplay.org/jq?q=if%20unique%5B1%5Dthen.%5Bindex(min)%5D%2b=1else.%2b%5B1%5Dend&j=%5B3,4,9,3%5D)
[Answer]
# PHP, 79 bytes
```
function i($a){max($a)>($n=min($a))?$a[array_search($n,$a)]++:$a[]=1;return$a;}
```
I think this needs no explanation.
[Answer]
## Groovy - 45 bytes
A groovy closure which accepts a list of Integer as input - please note this modifies the input `List`.
`{o->(o-o[0])?o[o.indexOf(o.min())]+=1:o<<1;o}`
Test cases can be seen here:
<http://ideone.com/9vRd9e>
Alternative of 56 bytes if the code needs to work with `int[]` or `List<Integer>`:
`{o=it.toList();(o-o[0])?o[o.indexOf(o.min())]+=1:o<<1;o}`
[Answer]
# [Actually](https://github.com/Mego/Seriously), 18 bytes
The algorithm used in this answer is largely based on [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/101421/47581). Golfing suggestions welcome! [Try it online!](https://tio.run/nexus/actually#@29t7etQqlxonetweK2Bw7mNhg6Fh5b@/x9tqmMMgbEA "Actually – TIO Nexus")
```
;;M@u#q;m@í0@α1@q¥
```
**Ungolfing**
```
      Implicit input a.
;;    Duplicate a twice.
M     Get the maximum of a.
@u#   Increment all of a and convert back to a list.
q;    Append max(a) to the end of a_plus_one, and duplicate. Call it b.
m@í   Get index of the minimum of b. Call it min_index.
        If all elements of a were equal, this is the maximum at the end.
        Else, it's somewhere else in the array.
0@α   Push a list of min_index zeroes.
1@q   Append a 1 to the end. Call this array c.
        This will increment at the desired index or otherwise append a 1.
¥     Pairwise add a and c to get our incremented array.
      Implicit return.
```
[Answer]
# [Tcl](http://tcl.tk/), 114 bytes
```
proc I a {if [llength [set S [lsort -u $a]]]<2 {lappend a 1} {lset a [lsearch $a [set m [lindex $S 0]]] [incr m]}}
```
[Try it online!](https://tio.run/##XY/BCoMwEETv@Yo5eC3U1B5a@gOePVoPIaZViDFohELIt9td1B5KCJndecNugrbr6qdRo4RC7F@orTXuHTrUswmoqJ7HKeC0IFNN0zwkolXeG9dSIE9UMaeYM2rSHWFbdKBW71rzQVbhTFHUvdMThial1Q7K80AR8ySipJuD1QX7SYJbbEg22DkI@XvlnpAbUODGwVj8qYLU9VCCVvZLmGnP@xN1yd9KYv0C "Tcl – Try It Online")
[Answer]
# [Vim](https://www.vim.org), 49 bytes
```
y$i,<esc>:s/^\(,\d*\)\1*$/&,0
/\<<C-r>=min([<C-r>"])
\>
f0<C-a>|x
```
Takes the array as comma-separated integers in the buffer. [Try it online!](https://tio.run/##K/v/v1IlU8cmtTjZzqpYPy5GQycmRStGM8ZQS0VfTceASz/GxsZZt8jONjczTyMazFSK1eSKseNKMwDyEu1qKv7/N9IxNtQx1jH8r1sGAA "V (vim) – Try It Online")
### Explanation
```
y$i,<esc>
```
Yank the original list of integers; then insert an extra comma at the beginning.
```
:s/^\(,\d*\)\1*$/&,0<cr>
```
Using regex, determine if the entire line consists of the same number. If so, append `,0`.
```
/\<...\><cr>
```
Find the first match of `...` as a full word (`\<` and `\>` represent word boundaries, corresponding to `\b` in PCRE), where `...` is:
```
<C-r>=min([<C-r>"])<cr>
```
Using the expression register, calculate the minimum of the original list.
If the original list was heterogeneous, the cursor is now on the number we want to increment. If the original list was all equal, however, we want to increment the 0 at the end, so:
```
f0
```
Move to the next occurrence of `0` on the line. If there is no `0`, this does nothing.
```
<C-a>|x
```
Increment the number under the cursor. Go to the beginning of the line and delete the extra comma.
[Answer]
# [Factor](https://factorcode.org/), 77 bytes
```
[ dup all-eq? [ 1 suffix ] [ dup [ ] infimum-by* 1 + swap pick set-nth ] if ]
```
[Try it online!](https://tio.run/##RY65jsJAEERzvqJikJE4gl0ICBEJCSKyHPSaHjNi3B7mEPau@HbvcKulUrXeC0pRGRrX73eb7XqByjXRaqlQsbAjo38p6EY8TuyEDTyfI0vJ/tPG3AZHHjWFI6zjEDrrtAQsB4M/THBNOb3n5PnN3nd9KNOn9MIfcY7vm9bnOEQLMibj8wp54j4qpVsUeKA8NS1K17HOfrphEkbwF7KwujylsSGTNC85CkX/BSFrTYexR2mYXP8P "Factor – Try It Online")
Went through a bunch of different iterations of this. `tri` was shorter than stack shufflers, amazingly, when using `change-nth`, but locals were king. However, we can attain even fewer bytes by using `infimum-by*`, which places both the index and value of the smallest element on the stack.
[Answer]
# [Julia 1.8](https://julialang.org), 44 bytes
```
!x=allequal(x) ? [x;1] : (x[argmin(x)]+=1;x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBBDoIwEEX3PcXAqsS6aIFEJcSDNF00EUxNrQol6V3csOFQbj2JBasEYzf_v5dM0pn7cOq0kn0_dLZebx4kcqXUurp1UmOXwB64K6iAHWDHZXM8K-O1WJW0cEmYedqqtS2UwBGngiDOCLAxaUjPk099zpUtKgs1XdQ01IzANlD2n7KR8l_KvyQQqi8NWFAGpv8i8O_aKGNxHMUEbDIbbXDs9_E28royh_emnyu9AA)
`allequal` requires julia 1.8 or later
[Answer]
# [Arturo](https://arturo-lang.io), ~~60~~ 56 bytes
```
$->a->([]=a--a\0)?->a++1[i:index a min a a\[i]:a\[i]+1a]
```
[Try it](http://arturo-lang.io/playground?EFj7yY)
[Answer]
# [Scala](https://www.scala-lang.org/), 159 bytes
Golfed version. [Try it online!](https://tio.run/##RU9Na4QwEL37Kx57SthdaehNO8IeC20vPZZSphrdtDG6MSwW8bfbaKE7DPPx3mM@hpItL93nly4Dntk46DFoVw049T2mJLmyRZ2dvOeft0cX3qm41aCFqZgqXaMRNnsyQ9hweSvJouVQnqeSB40xyy4wNUYiTlvjqBDjXsmI5v88FTE24iL/oA8qXoydc1MLTqs41rgypFa7JpyJlORsr6BtVDZRELp1s4x5u3JegCt7eBA2QNwfoKLLPAHqzkMYPByhEDqoOxkfRrRVXgsvt6b3xgXrhE/b79cQm0bsDtjJlZ2TZF5@AQ)
```
a=>{def g(l:List[Int]):List[Int]=l match{case x::q if x==a.min=>(x+1)::q;case x::q=>x::g(q);case _=>Nil};if(a.distinct.length==1)a:+1 else g(a.toList).toArray}
```
Ungolfed version. [Try it online!](https://tio.run/##bVHLSsQwFN33Kw6zSrAOFnfVCrMU1I3gRlzETtqJpumQBqnIfHs9SQtW8RKS@zj3dTLUyqpp6l/fdB1wr4yDHoN2@wG74xFfWQbsdQPjaq877cLOe/UplPclkvp868KLXBuomAbKh7LojHviU4EZWxopEAu2wpohlLjjndJydCWoyJWPeRGFToX6sFQFajVojChLjANMQ7Wq0KG6gRhxhkLOof/QP0J0crZiHNhartEPxuK3EE1nwpzSzbaRhO2e45GbsLXateEQJ2F/RlBykgTVliXbhA59XC1fWJG0E21ZrJpFwjw8d545vsxR8MgrRpreQxhcn6NA6FFcyIWNCP/zN37e5eiNC9YJ0v7@GGi0YpNjI@Xc7ZRN0zc)
```
object Main extends App {
  def incrementArray(arr: Array[Int]): Array[Int] = {
    val minVal = arr.min
    def g(list: List[Int], m: Int): List[Int] = list match {
      case x :: xs if x == m => (x + 1) :: xs
      case x :: xs           => x :: g(xs, m)
      case Nil               => Nil
    }
    if (arr.distinct.length == 1) arr :+ 1
    else g(arr.toList, minVal).toArray
  }
  var r = Array(3, 1, 1);
  for (i <- 1 to 10) {
    r = incrementArray(r)
    println(r.mkString(", "))
  }
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=,reduce -pa`, ~~75~~ 68 bytes
```
$F[(grep$_-$F[0],@F)?reduce{$F[$a]>$F[$b]?$b:$a}0..$#F:@F]++;$_="@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLVojvSi1QCVeF8g0iNVxcNO0L0pNKU1OrQYKqCTG2oGopFh7lSQrlcRaAz09FWU3Kwe3WG1ta5V4WyUHN6X//40VDBWMFUz@5ReUZObnFf/X9fXJLC6xsgotycyxhZj2X7cgMQcA "Perl 5 – Try It Online")
]