title: Wait, what language is this?

text:
# Question
Title: Wait, what language is this?
Recently I had the pleasure of writing a Haskell program that could detect if the `NegativeLiterals` extension was engaged. I came up with the following:

```
data B=B{u::Integer}
instance Num B where{fromInteger=B;negate _=B 1}
main=print$1==u(-1)

```

Try it online!

This will print `True` normally and `False` otherwise.

Now I had so much fun doing this I'm extending the challenge to all of you. What other Haskell language extensions can you crack?

## Rules

To crack a particular language extension you must write a Haskell program that compiles both with and without the language extension (warnings are fine) and outputs two different *non-error* values when run with the language extension and it turned off (by adding the `No` prefix to the language extension). In this way the code above could be shortened to just:

```
data B=B{u::Integer}
instance Num B where{fromInteger=B;negate _=B 1}
main=print$u(-1)

```

which prints `1` and `-1`.

Any method you use to crack a extension must be specific to that extension. There may be ways of arbitrarily detecting what compiler flags or LanguageExtensions are enabled, if so such methods are not allowed. You may enable additional language extensions or change the compiler optimization using `-O` at no cost to your byte count.

## Language extensions

You cannot crack any language extension that does not have a `No` counterpart (e.g. `Haskell98`, `Haskell2010`, `Unsafe`, `Trustworthy`, `Safe`) because these do not fall under the terms outlined above. Every other language extension is fair game.

## Scoring

You will be awarded one point for every language extensions you are the first person to crack and one additional point for every language extension for which you have the shortest (measured in bytes) crack. For the second point ties will be broken in favor of earlier submissions. Higher score is better

You will not be able to score a point for first submission on `NegativeLiterals` or `QuasiQuotes` because I have already cracked them and included them in the body of the post. You will however be able to score a point for the shortest crack of each of these. Here is my crack of `QuasiQuotes`

```
import Text.Heredoc
main=print[here|here<-""] -- |]

```

Try it online!

# Answer
> 27 votes
# MagicHash, 30 bytes

```
x=1
y#a=2
x#a=1
main=print$x#x

```

-XMagicHash outputs 1, -XNoMagicHash outputs 2

MagicHash allows variable names to terminate in a `#`. Therefore with the extension, this defines two functions `y#` and `x#` which each take a value and return a constant `2`, or `1`. `x#x` will return 1 (because it is `x#` applied to `1`)

Without the extension, this defines one function `#` which takes two arguments and returns `2`. The `x#a=1` is a pattern that never gets reached. Then `x#x` is `1#1`, which returns 2.

# 29 bytes

```
a=1
a#b=a
main|a<-0=print$a#0

```

# Answer
> 20 votes
# CPP, ~~33~~ 20 bytes

```
main=print$0-- \
 +1

```

Prints `0` with `-XCPP` and `1` with `-XNoCPP`.

With `-XCPP`, a slash `\` before a newline removes the newline, thus the code becomes `main=print$0-- +1` and only `0` is printed as the `+1` is now part of the comment.

Without the flag the comment is ignored and the second line is parsed as a part of the previous line because it is indented.

---

### Previous approach with `#define`

```
x=1{-
#define x 0
-}
main=print x

```

Also prints `0` with `-XCPP` and `1` with `-XNoCPP`.

# Answer
> 15 votes
# NumDecimals, 14 bytes

```
main=print 1e1

```

-XNumDecimals prints `10`. -XNoNumDecimals prints `10.0`.

# Answer
> 14 votes
# BinaryLiterals, 57 bytes

```
b1=1
instance Show(a->b)where;show _=""
main=print$(+)0b1

```

-XBinaryLiterals prints a single newline. -XNoBinaryLiterals prints a `1`.

I am sure there is a better way to do this. If you find one, please post it.

# Answer
> 13 votes
# MonomorphismRestriction + 7 others, 107 bytes

This uses TH which requires the flag `-XTemplateHaskell` at all times.

### File T.hs, 81 + 4 bytes

```
module T where
import Language.Haskell.TH
p=(+)
t=reify(mkName"p")>>=stringE.show

```

### Main, 22 bytes

```
import T
main=print $t

```

Compiling with the flag MonomorphismRestriction forces the type of `p` to `Integer -> Integer -> Integer` and thus produces the following output:

```
"VarI T.p (AppT (AppT ArrowT (ConT GHC.Integer.Type.Integer)) (AppT (AppT ArrowT (ConT GHC.Integer.Type.Integer)) (ConT GHC.Integer.Type.Integer))) Nothing"

```

Compiling with the flag NoMonomorphismRestriction leaves the type of `p` at the most general, ie. `Num a => a->a->a` \- producing something like (shortened the `VarT` names to `a`):

```
"VarI T.p (ForallT [KindedTV a StarT] [AppT (ConT GHC.Num.Num) (VarT a)] (AppT (AppT ArrowT (VarT a)) (AppT (AppT ArrowT (VarT a)) (VarT a)))) Nothing"

```

Try them online!

---

## Alternatives

Since the above code simply prints out the type of `p`, this can be done with all flags that somehow influence how Haskell infers types. I will only specify the flag and with what to replace the function `p` and if needed additional flags (besides `-XTemplateHaskell`):

### OverloadedLists, 106 bytes

Additionally needs `-XNoMonomorphismRestriction`:

```
p=[]

```

Either `p :: [a]` or `p :: IsList l => l`, try them online!

### OverloadedStrings, 106 bytes

Additionally needs `-XNoMonomorphismRestriction`:

```
p=""

```

Either `p :: String` or `p :: IsString s => s`, try them online!

### PolyKinds, 112 bytes

This is entirely due to @CsongorKiss:

```
data P a=P

```

Either `P :: P a` or `P :: forall k (a :: k). P a`, try them online!

### MonadComprehensions, 114 bytes

```
p x=[i|i<-x]

```

Either `p :: [a] -> [a]` or `p :: Monad m => m a -> m a`, try them online!

### NamedWildCards, 114 bytes

This one was found by @Laikoni, it additionally requires `-XPartialTypeSignatures`:

```
p=id::_a->_a

```

They both have the save type (`p :: a -> a`) but GHC generates different names for the variables, try them online!

### ApplicativeDo, 120 bytes

```
p x=do i<-x;pure i

```

Either `p :: Monad m => m a -> m a` or `p :: Functor f => f a -> f a`, try them online!

### OverloadedLabels, 120 bytes

This needs the additional flag `-XFlexibleContexts`:

```
p x=(#id)x
(#)=seq

```

Either types as `p :: a -> b -> b` or `p :: IsLabel "id" (a->b) => a -> b`, try them online!

# Answer
> 11 votes
# ScopedTypeVariables, ~~162~~ 113 bytes

```
instance Show[()]where show _=""
p::forall a.(Show a,Show[a])=>a->IO()
p a=(print::Show a=>[a]->IO())[a]
main=p()

```

-XScopedTypeVariables prints `""` (empty), -XNoScopedTypeVariables prints `"[()]"`.

Edit: updated solution thanks to useful suggestions in the comments

# Answer
> 11 votes
# CPP, ~~27~~ 25

```
main=print({-/*-}1{-*/-})

```

Try it online!

Prints `()` for `-XCPP` and `1` for `-XNoCPP`

***Previous version:***

```
main=print[1{-/*-},2{-*/-}]

```

Try it online!

Prints `[1]` with `-XCPP` and `[1,2]` otherwise.

Credits: This is inspired by Laikoni's answer, but instead of a `#define` it simply uses C comments.

# Answer
> 9 votes
# BangPatterns, 32 bytes

```
(!)=seq
main|let f!_=0=print$9!1

```

-XBangPatterns prints `1` whereas -XNoBangPatterns will print `0`.

This makes use that the flag BangPatterns allows to annotate patterns with a `!` to force evaluation to WHNF, in that case `9!1` will use the top-level definition `(!)=seq`. If the flag is not enabled `f!_` defines a new operator `(!)` and shadows the top-level definition.

# Answer
> 9 votes
# OverloadedStrings, ~~65~~ ~~48~~ 32 bytes

Taking advantage of RebindableSyntax, use our own version of fromString to turn any string literal into `"y"`.

```
main=print""
fromString _=['y']

```

Must be compiled with `-XRebindableSyntax -XImplicitPrelude`.

Without `-XOverloadedStrings` prints `""`; with prints `"y"`.

Also, it only just now struck me that the same technique works with (e.g.) OverloadedLists:

# OverloadedLists, 27 bytes

```
main=print[0]
fromListN=(:)

```

Must be compiled with `-XRebindableSyntax -XImplicitPrelude`.

Without `-XOverloadedLists` prints `[0]`; with prints `[1,0]`.

# Answer
> 9 votes
# MonoLocalBinds, GADTs, or TypeFamilies, ~~36~~ 32 bytes

EDIT:

* -4 bytes: A version of this was incorporated into the great polyglot chain by stasoid, who surprised me by putting all the declarations at top level. Apparently triggering this restriction does not require actual *local* bindings.

```
a=0
f b=b^a
main=print(f pi,f 0)

```
* With no extensions, this program prints `(1.0,1)`.
* With either of the flags -XMonoLocalBinds, -XGADTs, or -XTypeFamilies, it prints `(1.0,1.0)`.
* The `MonoLocalBinds` extension exists to prevent some unintuitive type inference triggered by GADTs and type families. As such, this extension is automatically turned on by the two others.
* It *is* possible to turn it off again explicitly with `-XNoMonoLocalBinds`, this trick assumes you don't.
* Like its more well-known cousin the monomorphism restriction, `MonoLocalBinds` works by preventing some values (~~in local bindings like `let` or `where`, thus the name~~ apparently it can also happen at top level) from being polymorphic. Despite being created for saner type inference, the rules for when it triggers are if possible even more hairy than the MR.
* Without any extension, the above program infers the type `f :: Num a => a -> a`, allowing `f pi` to default to a `Double` and `f 0` to an `Integer`.
* With the extensions, the type inferred becomes `f :: Double -> Double`, and `f 0` has to return a `Double` as well.
* The separate variable `a=0` is needed to trigger the technical rules: `a` is hit by the monomorphism restriction, and `a` is a *free variable* of `f`, which means that `f`'s binding group is not *fully generalized*, which means `f` is not *closed* and thus doesn't become polymorphic.

# Answer
> 9 votes
# RebindableSyntax, 25 bytes

I was reading the recently posted Guide to GHC's Extensions when I noticed an easy one that I didn't recall seeing here yet.

```
main|negate<-id=print$ -1

```

Also requires `-XImplicitPrelude`, or alternatively `import Prelude` in the code itself.

* `-XRebindableSyntax` changes the behavior of some of Haskell's syntactic sugar to make it possible to redefine it.
* `-1` is syntactic sugar for `negate 1`.
* Normally this `negate` is `Prelude.negate`, but with the extension it's "whichever `negate` is in scope at the point of use", which is defined as `id`.
* Because the extension is meant to be used to make replacements for the `Prelude` module, it automatically disables the usual implicit import of that, but other `Prelude` functions (like `print`) are needed here, so it is re-enabled with `-XImplicitPrelude`.

# Answer
> 8 votes
# ApplicativeDo, 146 bytes

```
newtype C a=C{u::Int}
instance Functor C where fmap _ _=C 1
instance Applicative C
instance Monad C where _>>=_=C 0
main=print$u$do{_<-C 0;pure 1}

```

Prints 1 when ApplicativeDo is enabled, 0 otherwise

Try it online!

# Answer
> 8 votes
# ApplicativeDo, 104 bytes

```
import Control.Applicative
z=ZipList
instance Monad ZipList where _>>=_=z[]
main=print$do a<-z[1];pure a

```

Try it online!

With `ApplicativeDo`, this prints

```
ZipList {getZipList = [1]}

```

Without it, it prints

```
ZipList {getZipList = []}

```

`ZipList` is one of the few types in the base libraries with an instance for `Applicative` but not for `Monad`. There may be shorter alternatives lurking somewhere.

# Answer
> 8 votes
# BinaryLiterals, ~~31~~ 24 bytes

Edit:

* -7 bytes: H.PWiz suggested adjusting it further by using a single `b12` variable.

An adjustment to H.PWiz's method, avoiding the function instance.

```
b12=1
main=print$(+)0b12

```

# Answer
> 7 votes
# Strict, ~~87 84~~ 82 bytes

-5 bytes thanks to dfeuer!

Could be less with `BlockArguments` saving the parens around `\_->print 1`:

```
import Control.Exception
0!_=0
main=catch @ErrorCall(print$0!error"")(\_->print 1)

```

Running this with -XStrict prints a `1` whereas running it with -XNoStrict will print a `0`. This uses that Haskell by default is lazy and doesn't need to evaluate `error""` since it already knows that the result will be `0` when it matched on the first argument of `(!)`, this behaviour can be changed with that flag - forcing the runtime to evaluate both arguments.

If printing nothing in one case is allowed we can get it down to **75 bytes** replacing the main by (also some bytes off by dfeuer):

```
main=catch @ErrorCall(print$0!error"")mempty

```

# StrictData, ~~106 99~~ 93 bytes

-15 bytes thanks to dfeuer!

This basically does the same but works with data fields instead:

```
import Control.Exception
data D=D()
main=catch @ErrorCall(p$seq(D$error"")0)(\_->p 1);p=print

```

Prints `1` with the -XStrictData flag and `0` with -XNoStrictData.

If printing nothing in one case is allowed we can get it down to **86 bytes** replacing the main by (19 bytes off by dfeuer):

```
main=catch @ErrorCall(print$seq(D$error"")0)mempty

```

---

**Note:** All solutions require `TypeApplications` set.

# Answer
> 7 votes
# ExtendedDefaultRules, ~~54~~ 53 bytes

```
instance Num()
main=print(toEnum 0::Num a=>Enum a=>a)

```

Prints `()` with `-XExtendedDefaultRules` and `0` with `-XNoExtendedDefaultRules`.

This flag is enabled by default in GHCi, but not in GHC, which recently caused some confusion for me, though BMO was quickly able to help.

The above code is a golfed version of an example in the GHC User Guide where type defaulting in GHCi is explained.

*-1 byte thanks to Ørjan Johansen!*

# Answer
> 6 votes
# Strict, 52 bytes

```
import GHC.IO
f _=print()
main=f$unsafePerformIO$f()

```

-XStrict

-XNoStrict

With `-XStrict`, prints `()` an extra time.

Thanks to @Sriotchilism O'Zaic for two bytes.

# Answer
> 6 votes
# StrictData, 58 bytes

```
import GHC.Exts
data D=D Int
main=print$unsafeCoerce#D 3+0

```

-XNoStrictData

-XStrictData

Requires `MagicHash` (to let us import `GHC.Exts` instead of `Unsafe.Coerce`) and `-O` (absolutely required, to enable unpacking of small strict fields).

With `-XStrictData`, prints 3. Otherwise, prints the integer value of the (probably tagged) pointer to the pre-allocated copy of `3::Integer`, which can't possibly be 3.

### Explanation

It will be a bit easier to understand with a little expansion, based on type defaulting. With signatures, we can drop the addition.

```
main=print
  (unsafeCoerce# D (3::Integer)
    :: Integer)

```

Equivalently,

```
main=print
  (unsafeCoerce# $
    D (unsafeCoerce# (3::Integer))
    :: Integer)

```

Why does it ever print 3? This seems surprising! Well, small `Integer` values are represented very much like `Int`s, which (with strict data) are represented just like `D`s. We end up ignoring the tag indicating whether the integer is small or large positive/negative.

Why can't it print 3 without the extension? Leaving aside any memory layout reasons, a data pointer with low bits (2 lowest for 32-bit, 3 lowest for 64-bit) of 3 must represent a value built from the third constructor. In this case, that would require a *negative* integer.

# Answer
> 5 votes
# DeriveAnyClass, ~~121~~ 113 bytes

Thanks to dfeuer for quite some bytes!

```
import Control.Exception
newtype M=M Int deriving(Show,Num)
main=handle h$print(0::M);h(_::SomeException)=print 1

```

-XDeriveAnyClass prints `1` whereas -XNoDeriveAnyClass prints `M 0`.

This is exploiting the fact that DeriveAnyClass is the default strategy when both DeriveAnyClass and GeneralizedNewtypeDeriving are enabled, as you can see from the warnings. This flag will happily generate empty implementations for all methods but GeneralizedNewtypeDeriving is actually smart enough to use the underlying type's implementation and since `Int` is a `Num` it won't fail in this case.

---

If printing nothing in case the flag is enabled replacing the `main` by the following would be **109 bytes**:

```
main=print(0::M)`catch`(mempty::SomeException->_)

```

# Answer
> 5 votes
# UnboxedTuples, 52 bytes

```
import Language.Haskell.TH
main=runQ[|(##)|]>>=print

```

Requires `-XTemplateHaskell`. Prints `ConE GHC.Prim.(##)` with -XUnboxedTuples and `UnboundVarE ##` with -XNoUnboxedTuples.

# Answer
> 5 votes
# OverloadedLists, 76 bytes

```
import GHC.Exts
instance IsList[()]where fromList=(():)
main=print([]::[()])

```

With -XOverloadedLists it prints `[()]`. With -XNoOverloadedLists it prints `[]`

This requires the additional flags: `-XFlexibleInstances`, `-XIncoherentInstances`

# Answer
> 5 votes
# HexFloatLiterals, ~~49~~ 25 bytes

*-24 bytes thanks to Ørjan Johansen.*

```
main|(.)<-seq=print$0x0.0

```

Prints `0.0` with `-XHexFloatLiterals` and `0` with `-XNoHexFloatLiterals`.

There are no TIO links because HexFloatLiterals was added in ghc 8.4.1, but TIO has ghc 8.2.2.

# Answer
> 5 votes
# ScopedTypeVariables, 37 bytes

```
main=print(1::_=>a):: ∀a.a~Float=>_

```

This also requires `UnicodeSyntax`,`PartialTypeSignatures`, `GADTs`, and `ExplicitForAll`.

Try it online (without extension)

Try it online (with extension)

### Explanation

The partial type signatures are just to save bytes. We can fill them in like so:

```
main=print(1::(Num a, Show a)=>a):: ∀a.a~Float=>IO ()

```

With scoped type variables, the `a` in the type of `1` is constrained to be the `a` in the type of `main`, which itself is constrained to be `Float`. Without scoped type variables, `1` defaults to type `Integer`. Since `Float` and `Integer` values are shown differently, we can distinguish them.

Thanks to @ØrjanJohansen for a whopping 19 bytes! He realized that it was much better to take advantage of the difference between `Show` instances of different numerical types than differences in their arithmetic. He also realized that it was okay to leave the type of `main` "syntactically ambiguous" because the constraint actually disambiguates it. Getting rid of the local function also freed me up to remove the type signature for `main` (shifting it to the RHS) to save five more bytes.

# Answer
> 4 votes
# PostfixOperators, 63 bytes

```
import Text.Show.Functions
instance Num(a->b)
main=print(0`id`)

```

Try it online (without extension)

Try it online (with extension)

This is a cut-down version of a Hugs/GHC polyglot I wrote. See that post for explanation. Thanks to @ØrjanJohansen for realizing I could use `id` instead of a custom operator, saving four bytes.

# Answer
> 4 votes
# StrictData, 97 bytes

```
import GHC.Generics
data A=A()deriving Generic
main=print$selDecidedStrictness$unM1.unM1$from$A()

```

Try it online (no strict data)

Try it online (strict data)

Also requires `DeriveGeneric`.

# Answer
> 4 votes
# DeriveAnyClass, 104 bytes

```
import Control.Exception
newtype M a=M a deriving(Show,Exception)
main=print.displayException$M Deadlock

```

Try it online (without extension)

Try it online (with extension)

Also requires `GeneralizedNewtypeDeriving`.

# Answer
> 4 votes
# TemplateHaskell, ~~140~~ 91 bytes

Just copied from mauke with small modifications. I don't know what's going on.

*-49 bytes thanks to Ørjan Johansen.*

```
import Language.Haskell.TH
instance Show(Q a)where show _=""
main=print$(pure$TupE[]::ExpQ)

```

Try it online!

# Answer
> 4 votes
# UnicodeSyntax, 33 bytes

```
(∀)=0
main|forall<-1=print(∀)

```

Try it online!

# Answer
> 3 votes
# MonomorphismRestriction, ~~31~~ 29 bytes

Edit:

* -2 bytes with an improvement by H.PWiz

```
f=(2^)
main=print$f$f(6::Int)

```

-XMonomorphismRestriction prints `0`. -XNoMonomorphismRestriction prints `18446744073709551616`.

* With the restriction, the two uses of `f` are forced to be the same type, so the program prints `2^2^6 = 2^64` as a 64-bit `Int` (on 64-bit platforms), which overflows to `0`.
* Without the restriction, the program prints `2^64` as a bignum `Integer`.

# Answer
> 2 votes
# ScopedTypeVariables, ~~119~~ 97 bytes

Just copied from mauke with small modifications.

Currently there are two other answers for ScopedTypeVariables: 113 bytes by Csongor Kiss and 37 bytes by dfeuer. This submission is different in that it does not require other Haskell extensions.

*-22 bytes thanks to Ørjan Johansen.*

```
class(Show a,Num a)=>S a where s::a->IO();s _=print$(id::a->a)0
instance S Float
main=s(0::Float)

```

Try it online!

# Answer
> 2 votes
# OverloadedStrings, 77 bytes

```
import Data.String
instance IsString Double where fromString _=0
main=print""

```

Try it online!

Other OverloadedStrings answers: by ბიმო, by felixphew. This one does not require other extensions. Created by Ørjan Johansen.

# Answer
> 1 votes
# NegativeLiterals, 20 bytes

```
main=print$ -1`mod`2

```

Try it online!

Copied from this answer.

# Answer
> 1 votes
# LexicalNegation, 20 bytes

```
main=print$ -1`mod`2

```

*(No TIO: ghc 8.2.2 \< 9.0.1)*

Same as NegativeLiterals.

# Answer
> 1 votes
# MonomorphismRestriction, 24 bytes

```
p=1
x=p+0.0
main=print$p
```

`-XMonomorphismRestriction` gives `1.0`

`-XNoMonomorphismRestriction` gives `1`

## Explanation

So here we have `p` which I assign to `1`. Now in Haskell `1` is a numeric literal and can be any `Num` type. Next we assign `x` to `p+0.0`, `0.0` is another literal, but it's a fractional literal so it has a more specific type than `1`. That's ok since `Fractional`s are also `Num`s. So `x` is just some fractional type. Then we print `p`.

So how does the monomorphism restriction come into play? Well since `p` doesn't have a type anotation, the compiler needs to come up with a type for `p`. With the monomorphism restriction this type is going to be concrete, i.e. it's going to come up with the first type it can rather than the most general kind. It sees that `p` is used as a fractional in the definition of `x` so it picks `Float` as the type for `p`. When we print `p` it's then printing a float, so it prints a decimal.

Without the monomorphism restriction the compiler takes some extra time and figures out that there is a polymorphic type that can be given to `p`. So it assigns it the polymorphic type `Num a => a` rather than `Float`. It then doesn't matter what's going on in `x` as long as it type checks it can't influence the type of `p`. When we print `p` at the end then the compiler once again has to guess a concrete type, however since the type is fully polymorphic it can choose its preferred default of `Int` and thus it prints `1` as an `Int` *without* the decimal place.

So here we are using type defaulting to control the type of the object that gets printed. Since `1` prints differently as a `Float` and an `Int` this results in different output.

---
Tags: code-challenge, decision-problem, polyglot, haskell
---


title: Sort every dimension

text:
# Question
Title: Sort every dimension
Given a multidimensional, rectangular array of nonnegative integers, sort it at every depth (lexicographically), starting from the innermost.

For example, with this array:

```
[ [ [5, 1, 4],
    [10, 7, 21] ],
  [ [9, 20, 2],
    [4, 2, 19] ] ]

```

You'd sort at the deepest first:

```
[ [ [1, 4, 5],
    [7, 10, 21] ],
  [ [2, 9, 20],
    [2, 4, 19] ] ]

```

Then sort at the next depth, lexicographically:

```
[ [ [1, 4, 5],
    [7, 10, 21] ],
  [ [2, 4, 19],
    [2, 9, 20] ] ]

```

lexicographic comparison of arrays means comparing the first element, and if they're equal comparing the second, and so on all the way down the line. Here we see that `[2, 4, 19]` is less than `[2, 9, 20]` because although the first elements are equal (2) the second aren't - 4 \< 9.

Finally, sort at the top depth (lexicographically):

```
[ [ [1, 4, 5],
    [7, 10, 21] ],
  [ [2, 4, 19],
    [2, 9, 20] ] ]

```

The first one is less than the second, because `[1, 4, 5]` is less than `[2, 4, 19]` because 1 is less than 2.

You may take the lengths of dimensions and/or depth of the array as well.

## Testcases

```
[2, 1] -> [1, 2]
[[[10, 5, 9], [6, 4, 4]], [[2, 6, 3], [3, 3, 2]], [[3, 8, 6], [1, 5, 6]]] -> [[[1, 5, 6], [3, 6, 8]], [[2, 3, 3], [2, 3, 6]], [[4, 4, 6], [5, 9, 10]]]
[[[6, 9], [12, 17]], [[9, 6], [9, 8]]] -> [[[6, 9], [8, 9]], [[6, 9], [12, 17]]]
[[[9, 1], [2, 5]], [[8, 5], [3, 5]]] -> [[[1, 9], [2, 5]], [[3, 5], [5, 8]]]

```

# Answer
# Python 2, 30 bytes (@SurculoseSputum)

```
def f(L):L>f<map(f,L)<L.sort()
```

Attempt This Online!

#### Old Python 2, 32 bytes (@ovs)

```
f=lambda s:s>f<s.sort(key=f)or s
```

Attempt This Online!

#### Old Python 2, 33 bytes (@ovs)

```
f=lambda s:s>[]<s.sort(key=f)or s
```

Attempt This Online!

#### Old Python 2, 34 bytes

```
f=lambda s:s>=[]<s.sort(key=f)or s
```

Attempt This Online!

This works by side-effect (of in-place sort). It uses comparison to `[]` as a type check and chained comparison to short circuit (in-place sort returns `None`, so the chained comparison will always fail)
> 11 votes

# Answer
# Jelly, 6 bytes

```
ßŒḊ¡€Ṣ

```

Try it online!

## How it works

```
ßŒḊ¡€Ṣ - Main link f(M). Takes a multidimensional array M on the left
    €  - Over each inner element E of M:
 ŒḊ    -   Get its depth, D
ß  ¡   -   Call f(E) D times
     Ṣ - Sort the result

```

Essentially, as sorting is idempotent, `f` is also idempotent, and so we can apply it as many times as we want with no extra side effects. Therefore, we iterate over each element of `M`, depth-wise, apply `f` to it, then sort the result.
> 7 votes

# Answer
# Wolfram Language (Mathematica), 18 bytes

```
Sort//@#/.Sort->D&

```

Try it online!

Essentially copied from this earlier answer. Relies on the array being rectangular; otherwise, `LexicographicSort` (introduced 12.3) is required instead

```
Sort//@#            sort all levels
        /.Sort->D   un-Sort atoms

```
> 7 votes

# Answer
# APL (Dyalog Extended), ~~18~~ 12 bytes

Anonymous prefix lambda. Takes list of lists… as argument.

```
{×≡⍵:∧∇¨⍵⋄⍵}

```

Try it online!

`{``}` "dfn"; argument is :

`×` \[if\] signum of
depth of
argument
`:` (i.e. if the argument has depth) then:

sort the
recursion on
`¨` each of
the argument

else:

return the argument
> 6 votes

# Answer
# SWI-Prolog, ~~72~~ ~~59~~ 49 bytes

```
f([H|T],S):-f(H,Q),f(T,R),msort([Q|R],S).
f(E,E).

```

Try it online!
> 4 votes

# Answer
# JavaScript, ~~70~~ 64 bytes

```
f=x=>x.sort(g=(a,b)=>1/a?a-b:f(a).some((c,i)=>a=g(c,f(b)[i]))*a)

```

Try it online!

*Saved 6 bytes thanks to tsh.*
> 3 votes

# Answer
# Vyxal, 6 bytes

```
λ-[vxs

```

Try it Online!

*-5 thanks to @emanresuA in vychat*

## Explained

```
λ-[vxs
λ      # a lambda that takes a single argument n and:
 -     #   subtracts n from itself (scalars return 0 which is falsey, lists return a list of 0s which is truthy) - borrowed from https://codegolf.stackexchange.com/a/241658/78850
  [    #  and if that item is a list
   vx  #    call this lambda on each item
     s #    and sort the result

```
> 3 votes

# Answer
# Pari/GP, 34 bytes

```
f(a)=if(#a',vecsort(apply(f,a)),a)

```

Try it online!
> 3 votes

# Answer
# Python 3,  ~~47~~  36 bytes

Saved 1 byte thanks to @Dialfrost, and 9 bytes thanks to @loopywalt

```
f=lambda l:l*0!=0==l.sort(key=f)or l

```
> 3 votes

# Answer
# Ruby, 30 bytes

```
f=->b{b*0==0?b:b.map(&f).sort}

```

Try it online!
> 3 votes

# Answer
# , 30 bytes

```
[:><@#\.@$(4 :'/:"x~y')&.>/@,<

```

Try it online!

Uses a single fold to explicitly sort each rank, in order. Requires an explicit verb since rank `"` is a conjunction.

*Note: Could save 1 byte with `{{ }}` but it fails on TIO's J version.*

# , 23 17 bytes, port of Adam's recursive APL solution

```
[:/:~$:^:(#@$)"_1

```

Try it online!

*-6 thanks to ovs!*
> 2 votes

# Answer
# Haskell + hgl, 15 bytes

```
x=Fe<sr<m x*~|p

```

Takes input as a free monad of lists.

## Explanation

In Haskell we use a free monad of lists. A very simplified definition would look like:

```
data Ragged a
  = Pur a
  | Fe [Ragged a]

```

It's either a terminal element (wrapped in `Pur`) or a list of more ragged lists (wrapped in `Fe`).

We could write the code then like:

```
x (Fe y)=
  Fe < sr < m x $ y
x (Pur y)=
  p y

```

In the `Fe` case we map `x` across the input to sort all lower levels, sort the result and wrap it back in a free.

In the pure case we just wrap it back in a pure using `p`.

Now hgl has a special operator to do this sort of case for us. We use the `*~|` operator which is the equivalent to a pattern match on the cases of a `Free`.

So now we rewrite both options as a function `Fe<sr<m x` and `p` and supply them as args to `*~|`.

We can't get rid of the `x=` this time because the definition is recursive.

## Reflections

Wow, I couldn't get this one in point free. That's probably an issue.

`hoF` for `hoistFree` *nearly* is useful here. If we just wanted to for example reverse every level `hoF rv` would work fine. But we can't just place `sr` in there instead of `rv`. `sr` needs the elements to be `Ord`. Instead we have to do this.

There should probably be a version of hoist which allows this sort of thing. Would save 9 bytes here.

```
maF ::
  ( Functor f
  , Functor g
  )
    => (f (Free g a) -> g (Free g a)) -> Free f a -> Free g a

```
> 2 votes

# Answer
# BQN, 13 bytesSBCS

```
⊢{∧⚇}´≡-↕∘≡

```

Run online!

`{∧⍟≡¨}` is a translation of J, `{×≡?∧¨;}` is a shorter direct translation of dyalog extended, but using the depth modifier is cooler.

-2 from Adam.
> 2 votes

# Answer
# 05AB1E, 15 bytes

```
"Ð˜Êi®δ.V}{"©.V

```

Try it online or verify all test cases.

**Explanation:**

As mentioned in similar challenges, 05AB1E lacks recursive functions unfortunately, making it pretty long by mimicking the behavior with a string and 05AB1E-eval.

```
"..."       # Push the recursive string mentioned below
     ©      # Store it in variable `®` (without popping)
      .V    # Evaluate and execute it as 05AB1E code
            # (after which the result is output implicitly)

Ð˜Ê         # Check that this is the maximum depth of this (inner) list:
Ð           #  Triplicate the current list
 ˜          #  Flatten the top copy
  Ê         #  Check that the top two copies are NOT equal
   i    }   # If this is truthy, so we've reached the maximum depth:
     δ      #  Map over each inner item:
    ® .V    #   Do a recursive call (by 05AB1E-evaluating string `®`)
         {  # Sort the list

```
> 2 votes

# Answer
# Julia 1.0, 22 bytes

```
!x::Int=x
!x=sort(.!x)

```

Try it online!
> 2 votes

# Answer
# Charcoal, 49 bytes

```
⊞υθＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＷ∧υ⊟υ«≔⟦⟧ηＷι⊞η⊟ιＷ⁻ηιＦ№η⌊κ⊞ι⌊κ»Ｉθ

```

Try it online! Link is to verbose version of code. Outputs using Charcoal's default output format, where depth 1 arrays print their elements on their own line but the arrays themselves are double-spaced from each other, then depth 2 arrays are triple-spaced from each other etc. Explanation:

```
⊞υθ

```

Start enumerating all of the arrays at each depth.

```
ＦυＦι

```

Process all elements of each array.

```
Ｆ⁼κ⁺⟦⟧κ⊞υκ

```

If this element is itself an array then push it to the list of all arrays.

```
Ｗ∧υ⊟υ«

```

Process the list in reverse order.

```
≔⟦⟧ηＷι⊞η⊟ι

```

Move the elements from this array into a temporary array.

```
Ｗ⁻ηιＦ№η⌊κ⊞ι⌊κ

```

Move them back in ascending order.

```
»Ｉθ

```

Output the final array.
> 1 votes

# Answer
# Fig, \\$7\log\_{256}(96)\approx\\$ 5.762 bytes

```
!#lxKMX

```

See the README to see how to run this

This answer uses that fact that programs = functions in Fig, so I can invoke the program from within the program.

```
!#lxKMX # Takes the list as input
!       # If
 #lx    # The input is a list
     M  # Map the list
      X # By this function (i.e. the program itself)
    K   # Then sort the resulting list
        # If the input is not a list, simply return the input

```
> 1 votes

---
Tags: code-golf, array, sorting
---


title: Quartic Summation

text:
# Question
Title: Quartic Summation
# Guidelines

### Task

Given two non-negative integers, find the sum of both numbers... to the power of 4.

---

### Examples

`2, 3 -> 97` (2^4 + 3^4 = 97)

`14, 6 -> 39712` (14^4 + 6^4 = 39712)

`0, 25 -> 390625` (0^4 + 25^4 = 390625)

---

### Rules

* You will only ever receive two non-negative integers as input (bonus points if you get it to work with negative integer input).
* You can take the input however you would like (arrays, list, two separate arguments, comma-separated string)
* You can either output your answer as a number or a string.
* As this is code golf, the shortest answer in bytes will win.

# Answer
> 7 votes
# Regex  `m` (PCRE2 v10.35 or later), 10 bytes

```
^(?*x+){4}

```

Attempt This Online! \- PCRE2 v10.40+

Takes its input in comma-delimited unary, as a concatenation of strings of `x` characters whose lengths represent the numbers, separated by `,` characters. (Bonus: The number of arguments is variable, not just 2.) Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)

`^` anchors the expression to the beginning of each line, making it process each number in the list exactly once, thanks to the `m`ultiline flag. The result of each adds to the total (instead of multiplying the total), since they are independent matches not done in concert.

Non-atomic lookahead, added to PCRE2 in v10.34 as `(*napla:`...`)` and given the `(?*`...`)` synonym in v10.35, makes calculating \\$n^k\\$, where \\$k\\$ is a constant, very easy in -regex. `(?*x+){4}` is equivalent to `(?*x+)(?*x+)(?*x+)(?*x+)`. Each `(?*x+)` essentially picks a number in \\$\[1,n\]\\$, cycling through all the values effectively independently of the others, so the number of possible choices that lead to a full match is \\$n^4\\$.

It would not be possible to emulate this kind of solution using lookbehind with recursion to emulate variable-length-lookbehind, because that requires using lookahead nested inside lookbehind, both of which are atomic – so only one possible match would be tried. And even if it were not for that problem, the engine will complain of "nested recursion at the same subject position", which is unavoidable.

# Regex  (PCRE / Raku`:P5`), 27 bytes

```
(|xxx|((||){2}||)xx?)x*x*x+

```

Try it online! \- PCRE1
Try it online! \- PCRE2 v10.33 / Attempt This Online! \- PCRE2 v10.40+
Try it online! \- Raku (Perl 6)

```
(
                 # apply once with tail = N
|
    xxx          # apply once with tail = N-3
|
    ((||){2}||)  # apply 3**2+2==11 times...
    xx?          # ...with tail = N-1 or N-2
)
x*x*x+           # tail'th pentatope number

```

Although PCRE and Raku are the only regex engines currently capable of counting this regex's number of possible matches without their source code being patched, this regex itself only uses a **POSIX ERE** level of functionality, so is in theory universally compatible with all regex engines.

Lacking non-atomic lookahead, the only golf-efficient way I can think of to cause the number of possible matches to be \\$n^k\\$, where \\$k\\$ is a constant, is to decompose \\$n^k\\$ into a sum of \\$n\\$-simplex numbers. \\$4\\$-simplex numbers have the formula \\$S\_4(n)=n(n+1)(n+2)(n+3)/24\\$. So what we want is to solve is:

$$n^4=a⋅S\_4(n)+b⋅S\_4(n-1)+c⋅S\_4(n-2)+d⋅S\_4(n-3)$$

for \\$a,b,c,d\\$. The general form of this turns out to have the \\$k\\$th Euler's triangle row as its solution. In the case of \\$n^4\\$, this is \\$1,11,11,1\\$.

The -regex for \\$S\_4(n)\\$ is `x*x*x+`: Try it online!

What we need to do is have it match \\$1\\$ time on \\$n\\$, \\$11\\$ times on \\$n-1\\$, \\$11\\$ times on \\$n-2\\$, and \\$1\\$ time on \\$n-3\\$.

Multiplying the number of possible matches of a subexpression can be done simply by concatenating, for example, `(|||)` to multiply by \\$4\\$. As a standalone regex returning \\$4(n+1)\\$, this can simply be `|||`: Try it online! \- note that this is \\$4(n+1)\\$ because an empty regex returns \\$n+1\\$ possible matches.

The simplest choice for multiplying by \\$11\\$ would be `(||||||||||)`, but it turns out this can be optimized down to `((||){2}||)`, as \\$11=3^2+2\\$, where `(||){2}` is \\$3^2\\$ and each additional `|` adds \\$1\\$. Larger numbers can be additionally optimized by factorization. Additionally, there's expressions like `(|){3,5}` for \\$56=2^3+2^4+2^5\\$.

So, `((||){2}||)xx?` is the part where it's creating \\$11\\$ possibilities each, `((||){2}||)`, in which the subsequent expression is evaluated on \\$n-1\\$ or \\$n-2\\$, using `xx?`.

The first several n-simplex functions are as follows, in -regex:

\\$S\_0(n)\\$: `^` (returns \\$1\\$)
\\$S\_1(n)\\$: `x` (returns \\$n\\$)
\\$S\_2(n)\\$: `x+` (triangular numbers)
\\$S\_3(n)\\$: `x*x+` (tetrahedral numbers)
\\$S\_4(n)\\$: `x*x*x+` (pentatope numbers)
\\$S\_5(n)\\$: `x(x*){4}`
\\$S\_6(n)\\$: `x(x*){5}`

The first several \\$n^k\\$ are as follows:

\\$n^0\\$: Try it online! `^`
\\$n^1\\$: Try it online! `x`
\\$n^2\\$: Try it online! `x?x+` (squares)
\\$n^3\\$: Try it online! `(|xx|(|||)x)x*x+` (cubes)
\\$n^4\\$: Try it online! `(|xxx|((||){2}||)xx?)x*x*x+`
\\$n^5\\$: Try it online! `x(|x{4}|x((||||){2}|)(|xx)|((|){6}||)xx)(x*){4}`
\\$n^6\\$: Try it online! `x(|x{5}|x((|){3,5}|)(|xxx)|(|)((||||){2,3}|)xxx?)(x*){5}`
\\$n^7\\$: Try it online! `x(|x{6}|x(|){3,6}(|x{4})|xx(||)((||||||){2,3}|||||)(xx)?|xxx(|){4}((||||){2,3}|))(x*){6}`
\\$n^8\\$: Try it online! `x(|x{7}|x((||){5}||||)(|x{5})|xx(||){4}((|){4,5}|||||)(|xxx)|xxx((|){8}((|){2,5}|)|||)x?)(x*){7}`

Perl 5 severely undercounts the number of possible matches (Attempt This Online); see below for a workaround. But Raku's Perl 5 compatibility mode (`:P5` adverb) fully evaluates every choice path (and not just due to its `:ex`haustive adverb – it does the same without it).

# Regex  (Perl / PCRE / Raku`:P5`), 30 bytes

```
(|xxx|(()||||||||||)xx?)x*x*x+

```

Try it online! \- Perl v5.28.2 / Attempt This Online! \- Perl v5.36+
Try it online! \- PCRE1
Try it online! \- PCRE2 v10.33 / Attempt This Online! \- PCRE2 v10.40+
Try it online! \- Raku (Perl 6)

The part in the 27 byte version that is undercounted by Perl is `((||){2}||)`, the expression that multiplies possibilities by 11.

Perl forces *any* loop to exit after making a zero-width match (whereas PCRE only does so on loops whose quantifier has no maximum, which I think is more logical), so `(||){2}` needs to be changed to `(||)(||)`, adding 1 byte.

Perl prunes a group's alternatives down to one if they are all identical, but doesn't do this if even one alternative differs from the others. So `(||)` needs to be changed to `(()||)` in both places, adding 4 bytes.

After all that, it becomes `((()||)(()||)||)`. But that's longer than `(()||||||||||)`, so we use the latter instead, at just 3 bytes longer than `((||){2}||)`.

# Regex  `m` (PCRE), ~~73~~ 69 bytes

Without decomposing a fourth power into pentatope numbers, I'm pretty sure this is the best solution possible (it might golf down a tiny bit more than this, but not much):

```
^(?=(x*)\1{3}(xx())?(x())?)((?=\1(x*))(x+(|||)|\3(|)|\5).*(?=\7$)){4}

```

Try it online! \- PCRE2 v10.33 / Attempt This Online! \- PCRE2 v10.40+

```
^                    # tail = N = input number
(?=
    (x*)\1{3}        # \1 = floor(tail / 4)
    (()xx)?(()x)?    # \3,\5 = {tail % 4} in binary:
                     # \3 set|unset = 2's place digit 1|0
                     # \5 set|unset = 1's place digit 1|0
)
(
    # Manipulate the number of possible matches to be exactly \1 * 4 + \2 == N
    (?=\1(x*))       # \7 = tail - \1
    (
        x+(|||)      # Add \1 * 4 to the number of possibilities of this iteration
    |
        \3(|)|\5     # Add \3*2 + \5 (where set=1 and unset=0) to the number of
                     # possibilities of this iteration
    )
    .*(?=\7$)        # tail = \7, i.e. the next multiple of \1 down from what it
                     # was when \7 was captured above.
){4}                 # Iterate the above 4 times, such that after finishing, each
                     # iteration could have been at any one of the N states.

```

This method does eventually win out against simplex decomposition:

1: `x`
`x`

2: `x?x+`
`^(?=(x*)\1(x()|))\2(x+(|)|\3).*(?=\1$)(?4)`

3: `(|xx|(|||)x)x*x+`
`^(?=(x*)\1\1(x())?(x())?)((?=\1(x*))(x+(||)|\3|\5).*(?=\7$)){3}`

4: `(|xxx|((||){2}||)xx?)x*x*x+`
`^(?=(x*)\1{3}(xx())?(x())?)((?=\1(x*))(x+(|||)|\3(|)|\5).*(?=\7$)){4}`

5: `x(|x{4}|x((||||){2}|)(|xx)|((|){6}||)xx)(x*){4}`
`^(?=(x*)\1{4}(xx())?(x())?(x())?)((?=\1(x*))(x+(||||)|\3(|)|\5|\7).*(?=\9$)){5}`

6: `x(|x{5}|x((|){3,5}|)(|xxx)|(|)((||||){2,3}|)xxx?)(x*){5}`
`^(?=(x*)\1{5}(xx())?(xx())?(x())?)((?=\1(x*))(x+(|||||)|\3(|)|\5(|)|\7).*(?=\9$)){6}`

7: `x(|x{6}|x(|){3,6}(|x{4})|xx(||)((||||||){2,3}|||||)(|xx)|xxx(|){4}((||||){2,3}|))(x*){6}`
`^(?=(x*)\1{6}(xxx())?(xx())?(x())?)((?=\1(x*))(x+(||||||)|\3(||)|\5(|)|\7).*(?=\9$)){7}`

8: `x(|x{7}|x((||){5}||||)(|x{5})|xx(||){4}((|){4,5}|||||)(|xxx)|xxx((|){8}((|){2,5}|)|||)x?)(x*){7}`
`^(?=(x*)\1{7}(x{4}())?(xx())?(x())?)((?=\1(x*))(x+(|){3}|\3(|||)|\5(|)|\7).*(?=\9$)){8}`

# Answer
> 6 votes
# CP-1610 assembly, 30 DECLEs = 38 bytes

Let's try this on a processor lacking a multiply instruction. This code is intended to be run on an Intellivision.

CP-1610 instructions are encoded with 10-bit values, known as *'DECLE'* s. This subroutine is 30 DECLEs long, starting at $4808 and ending at $4825.

Takes input in registers *R0* and *R3*. Saves the result in *R2*.

```
                              ROMW  10            ; use 10-bit ROM
                              ORG   $4800         ; map program at address $4800

4800  02B8 000E               MVII  #14,    R0    ; example call
4802  02BB 0006               MVII  #6,     R3
4804  0004 0148 0008          CALL  addX4Y4
4807  0017                    DECR  PC            ; loop forever

4808  0275            addX4Y4 PSHR  R5            ; push the return address
4809  0004 0148 001A          CALL  square        ; compute R2 = R0^2
480C  0004 0148 0019          CALL  square2       ; compute R2 = R2^2
480F  0272                    PSHR  R2            ; push this result on the stack
4810  0098                    MOVR  R3,     R0    ; compute R2 = R3^2
4811  0004 0148 001A          CALL  square
4814  0004 0148 0019          CALL  square2       ; compute R2 = R2^2
4817  02F2                    ADD@  R6,     R2    ; add this result to the intermediate one
4818  02B7                    PULR  PC            ; return

4819  0090            square2 MOVR  R2,     R0    ; copy R2 to R0
481A  0081            square  MOVR  R0,     R1    ; copy R0 to R1
481B  01D2                    CLRR  R2            ; initialize R2 = result
481C  0200 0002               B     halve         ; start by halving R1
481E  00C2            add     ADDR  R0,     R2    ; add R0 to R2
481F  0048            loop    SLL   R0            ; double R0
4820  0079            halve   SARC  R1            ; halve R1
4821  0221 0004               BC    add           ; was the LSB set?
4823  022C 0005               BNEQ  loop          ; is R1 now equal to zero?
4825  00AF                    JR    R5            ; return

```

### Example run

Running the above code (with *R0* = 14 and *R3* = 6) gives:

```
> b 4807
Set breakpoint at $4807
> r
Hit breakpoint at $4807
 0900 0000 9B20 0006 01FE 4817 02F1 4807 S-----iq  DECR R7
           ^^^^

```

*R2* is set to $9B20, which is 39712 in decimal.

# Answer
> 4 votes
# Perl, 12 bytes

Includes `+1` for `p`

Works for 1 or more numbers each given on a separate line on STDIN

```
(echo 2; echo 3) | perl -pe '$\+=$_**4}{'

```

# Answer
> 4 votes
# Haskell, 11 bytes

```
sum.map(^4)

```

This is a function that takes the parameters as a list.

Try it online!

# Answer
> 3 votes
# Japt, 3 bytes

Takes input as an array of integers; can handle negatives and more than 2 integers at a time. Add `N` at the beginning to take input as individual integers.

```
xp4

```

Try it

---

## Explanation

`p4` raises each element to the power of 4 and `x` reduces by addition.

# Answer
> 3 votes
# \>\<\>, 11 bytes

```
:*:*$:*:*+n

```

Try it online!

Takes values through the `-v` flag. Dupe and multipy, dupe and multiply, and repeat with the other value before adding the two together and printing.

# Answer
> 3 votes
## Retina, 9 bytes

```
.+
****
_

```

Try it online!

Input should be linefeed-separated.

### Explanation

```
.+
****

```

`*` is Retina's repetition operator. It has implicit operands `$&` and `_`, respectively, so the substitution pattern is short for `$&*$&*$&*$&*_`. It's also right-associative, if the regex matches a decimal number **n**, this generates a string of **n4** underscores (i.e. a unary representation of the fourth power of **n**).

```
_

```

To sum the two results and convert the sum back to decimal, we simply count the number of underscores in the string.

# Answer
> 3 votes
# Pyt, 2 bytes

```
⁴Ʃ

```

Try it online!

Takes input as a list.

# Answer
> 2 votes
# APL (Dyalog Unicode), 5 bytesSBCS

Anonymous tacit prefix function. Takes a list as argument. The list may have any length and contain any numbers, even complex ones.

```
+.*∘4

```

Try it online!

`+.*` is a variant on matrix product, `+.×` as follows: `a b+.×c d` is `(a×c)+(b×d)` and `a b+.×c` is `(a×c)+(b×c)`. So `a b+.*c` is `(a*c)+(b*c)`. `*` is power.

`∘4` curry four as right argument. This results in a monadic function `(a*4)+(b*4)`.

# Answer
> 2 votes
# , 7 6 bytes

-1 byte thanks to Adám

```
1#.^&4

```

Try it online!

Works for lists with arbitrary length

`^&4` \- each item of the list to the 4-th power

`1#.` \- sum of all 4-th powers by base-1 conversion

Try it online!

## Alternative

# , 7 bytes

```
+/ .^4:

```

This is a variant of the matrix product, analogue of Adám's APL solution

Try it online!

# Answer
> 2 votes
# Python 3, 20 bytes

```
lambda x,y:x**4+y**4

```

# Answer
> 2 votes
# MATL, 3 bytes

```
K^s

```

Try it online!

This can handle more than two input values, as well as negative inputs.

### Explanation:

Fasten your seat belts, this might blow your mind!

```
       % Implicit input
K      % Push literal 4
 ^     % Raise each element of the input vector to the 4th power
  s    % Sum

```

Also works:

```
4^s    % Push 4 and raise input to it, then sum
UUs    % Square input twice, then sum

```

# Answer
> 1 votes
# JavaScript (ES7), 15 bytes

Does exactly what it says on the tin.

```
a=>b=>a**4+b**4

```

### Test cases

```
let f =

a=>b=>a**4+b**4

console.log(f(2)(3))
console.log(f(14)(6))
console.log(f(0)(25))
```

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
4mO

```

Try it online!

**Explanation**

```
4m    # raise each to the power of 4
  O   # sum

```

# Answer
> 1 votes
## C, C++ =\> 29 bytes

-1 byte thanks to Jonathan Frech

```
#define Q(a,b)a*a*a*a+b*b*b*b

```

Test cases :

```
#include <stdio.h>
int main() {
    printf("Q(%d,%d) = %d\n", 2, 3, Q(2, 3));
    printf("Q(%d,%d) = %d\n", 14, 6, Q(14, 6));
    printf("Q(%d,%d) = %d\n", 0, 25, Q(0, 25));
}

```

# Answer
> 1 votes
# Julia, 11 bytes

```
a$b=a^4+b^4

```

Try it online!

---

# Julia, 12 bytes

```
!a=sum(a.^4)

```

Try it online!

# Answer
> 1 votes
# Excel, 10 bytes

```
=A1^4+B1^4

```

Nothing to see here.

# Answer
> 1 votes
# C (gcc), 26 bytes

```
f(a,b){a=a*a*a*a+b*b*b*b;}

```

Try it online!

# Answer
> 1 votes
# Jelly, 3 bytes

```
*4S

```

Try it online!

# Answer
> 1 votes
# C (gcc), 0 + 24 bytes

Compile this code

```
main(){
    printf("%d\n",x(2,3));
    printf("%d\n",x(14,6));
    printf("%d\n",x(0,25));
}

```

With this flag:

```
-D=x(a,b)a*a*a*a+b*b*b*b

```

Try it online! (GCC Tio)
Try it online! (Bash Compile example)

# Answer
> 1 votes
# Triangularity, 31 bytes

```
...)...
..IEM..
.)4s^}.
u......

```

Try it online!

# Answer
> 1 votes
# , 16 bytes

```
pryr::f(x^4+y^4)

```

Try it online!

# Answer
> 1 votes
## Ruby, 16 bytes

```
->a,b{a**4+b**4}

```

Try It Online!

# Answer
> 1 votes
# Java 8, 21 bytes

```
a->b->a*a*a*a+b*b*b*b

```

Try it online.

# Answer
> 1 votes
# Perl 6, 9 bytes

```
*⁴+*⁴

```

Try it online!

# Answer
> 1 votes
# Pyth, 5

```
sm^d4

```

Online test.

```
  ^d4     # lambda to take 4th power
     Q    # implicit input
 m        # map lambda over input
s         # sum

```

# Answer
> 1 votes
# Attache, 8 bytes

```
Sum@`^&4

```

Try it online!

Takes input as a pair of integers.

## Explanation

This is a composition of two functions:

* `Sum`
* ``^&4`

The first executed is ``^&4`, which is equivalent to:

```
`^&4
RBond[`^, 4]
RBond[{_1 ^ _2}, 4]
{_1 ^ 4}

```

That is, a function that raises its argument to the fourth power. This vectorizes over the input array. Then, `Sum` takes the sum of these elements.

## Alternative approaches

```
Sum@`^&4@V    ?? 11 bytes, input is two arguments
{Sum[_^4]}    ?? 11 bytes, input is array
{_^4+_2^4}    ?? 11 bytes, input is two arguments

```

# Answer
> 1 votes
# Pyramid Scheme, 220 bytes

```
           ^
          / \
         /   \
        /  +  \
       /       \
      ^---------^
     /^\       /^\
    ^---^     ^---^
   /#\ /4\   /#\ /4\
  ^--- ---  ^--- ---
 /l\       /l\
/ine\     /ine\
-----     -----

```

Try it online!

`line` pyramids obtain a line from STDIN, `#` pyramids cast their arguments into numbers, `^` pyramids perform exponentiation, and the `+` pyramid adds two things together.

# Answer
> 1 votes
# Minkolang 0.15, 10 bytes

```
$n4;r4;+N.

```

Try it here.

## Explanation

```
$n4;r4;+N.
$n           take all input as numbers     [a, b]
  4;         raise to the fourth           [a, b^4]
    r        reverse stack                 [b^4, a]
     4;      raise to the fourth           [b^4, a^4]
       +     add                           [b^4 + a^4]
        N    output                        []
         .   terminate

```

# Answer
> 1 votes
# , 25 bytes

```
(int x,int y)=>x^^4+y^^4;

```

Try it online!

A simple lambda that performs exponentiation on each of its arguments, with `^^` being the exponentiation operator.

# Answer
> 1 votes
# Python 3, 20 bytes

```
lambda a,b:a**4+b**4

```

Try it online!

# Answer
> 0 votes
# IBM/Lotus Notes Formula, 17 bytes

```
@Sum(@Power(a;4))

```

Field formula that takes its input from a multi-value numeric field on the same form. Works because for most Formula functions, if a list is given as input then the formula will apply the given function recursively to every item in the list.

There is no TIO for Notes but here's a screenshot of one of the test cases:

# Answer
> 0 votes
# Add++, 8 bytes

```
L,4^$4^+

```

Try it online!

# Answer
> 0 votes
# Python 2, ~~30~~ 28 bytes

```
lambda i:sum(x**4for x in i)

```

Try it online!

Alternative approach for Python (albeit slightly longer than the more obvious one). Takes input as a list of integers.

-2 with thanks to @JonathanAllan

# Answer
> 0 votes
## Perl 6, 15 bytes

```
{$^a**4+$^b**4}

```

An anonymous lambda. Try It Online!

# Answer
> 0 votes
# APL+WIN, 5 bytes

Prompts for screen input of a two element vector. Seems to work for negative inputs

```
+/⎕*4

```

# Answer
> 0 votes
# Husk, 3 bytes

```
ṁ^4

```

Input as a list, try it online!

### Alternative, 4 bytes

One byte more but I like this more:

```
¤+^4

```

Expects two arguments, try it online!

# Answer
> 0 votes
# ,,,, 8 bytes

```
4*↔4*+

```

Try it online!

It's trivial enough for ,,,. :P

# Answer
> 0 votes
# CJam, 7 bytes

```
{4f#:+}

```

Try it online!

# Answer
> 0 votes
# Momema, 68 bytes

```
2*-8k03*2 2 01*3j02+*2*3 1+-1*1j=*1k*001k3 4*2 2*-8 02k2 03k1-8+*2*4

```

Try it online!

Doesn't work for zeroes. Awaiting clarification from OP.

## Explanation

```
2   *-8    #  o = read num
k   0      #  procedure square(o, LABEL):
3   *2     #    original = o
2   0      #    o = 0
1   *3     #    i = original
j   0      #    do {
2   +*2*3  #      o = o + original
1   +-1*1  #      i = i - 1
j   =*1    #    while (i != 0)
k   *0     #    goto LABEL
           #  LABEL = sq0
           #  square(o, LABEL); sq0:
0   1      #  LABEL = sq1
k   3      #  square(o, LABEL); sq1:
4   *2     #  t = o
2   *-8    #  o = read num
0   2      #  LABEL = sq2
k   2      #  square(o, LABEL); sq2:
0   3      #  LABEL = sq3
k   1      #  square(o, LABEL); sq3:
-8  +*2*4  #  print num t + o

```

This program defines a "procedure" which squares memory cell 2 (using 1 and 3 as temporary cells) and then jumps based on the value of cell 0.

# Answer
> 0 votes
# Physica, 13 bytes

```
=>a;b:a^4+b^4

```

## Demo

Note that physica is not on TIO yet. This is a lambda function, which can be called using `F[a; b]`, as follows:

# Answer
> 0 votes
# K4, 10 bytes

**Solution:**

```
+/xexp[;4]

```

**Example:**

```
q)k)+/xexp[;4]2 3
97f
q)k)+/xexp[;4]0 25
390625f

```

**Explanation:**

Pretty trivial...

```
+/xexp[;4] / the solution
  xexp[;4] / xexp does x^y, with y = 4
+/         / sum over

```

# Answer
> 0 votes
## Canvas, 6 bytes

```
４＾╶４＾＋

```

Try it here!

# Answer
> 0 votes
# Phoenix, 28 bytes

```
echo$argv[1]**4+$argv[2]**4;

```

Try it online!

Phoenix is a variant of PHP designed to be lightweight in terms of syntax. TO this end, it does a pretty okay job. A function would be longer, so this seems to be the shortest way. (The documentation is sparse, and I don't know much PHP myself.)

# Answer
> 0 votes
# Jelly, 4 bytes

```
,*4S

```

Try it online!

**Explanation**

```
,       pair
 *4     to the power of four
   S    sum

```

# Answer
> 0 votes
# Emojicode, 49 bytes

```
ij➡➕i 4j 4

```

Try it online!

---
Tags: code-golf, math, number, arithmetic
---


title: De-Nesting Lists

text:
# Question
Title: De-Nesting Lists
Given a list with lists nested inside it, return the list with the nested lists' items de-nested.

# Input

The list will have, at most, 4-deep nested lists. Count all 0's within the input as a null space.

# Output

Individually print out each item. Do not print out the output as a list. You can seperate each item with any kind of whitespace.

## Example Cases

`[[1, 0], [2, 0], [2, 3]] -> 1 2 2 3`
`[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]] -> 4 5 8 5 6 20 1 20 500`
`[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]] -> 1 1 1 2 2 2`

The shortest code wins.

# Answer
## APL (10)

```
0~⍨⍎⍞~'[]'

```

Explanation:

* `⍞~'[]'`: User input () without (`~`) the characters `'[]'`
This gives something like `'1,2,0,2,3'`
* : Evaluate this string. It so happens that `,` is the concatenation operator, so now we have a list: `1 2 0 2 3` (APL lists are whitespace-separated by default)
* `0~⍨`: Remove all the numbers 0 from this list. (It is a list of numbers, not of strings, by now, so zeroes within numbers are not removed.
* This value is output (by default, because it's the value of the whole program, kind of like Golfscript). APL lists are whitespace-separated by default so it looks exactly like in the question.
> 7 votes

# Answer
## Sed, 20 chars

Solution is based on POSIX Extended Regular Expression.

```
s;[^0-9]+0|[],[]+;;g

```

**Output**:

```
bash-3.2$ sed -rf sedFile <<< "[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]]"
4 5 8 5 6 20 1 20 500

```

**Edit**: POSIX Basic Regular Expression(@clueless's solution), **19 chars**:

```
s/[^0-9][^1-9]*/ /g

```
> 7 votes

# Answer
## Python, 45

w00, exception handling in golf!

```
def d(x):
 try:map(d,x)
 except:print`x`*(x!=0)

```
> 7 votes

# Answer
## Perl, 20 16 13 chars

```
perl -ple 's/\D+0?/ /g'

```

The `-l` switch is necessary to preserve the final newline in the output.

Here's an alternate version that actually works with the lists semantically (51 chars).

```
perl -E '$,=$";sub p{map{ref$_?p(@$_):$_||""}@_}say p eval<>'

```

Both of these programs take advantage of the problem's stipulation that it "can separate each item with any kind of whitespace", and replaces the zeros with blanks, instead of removing them outright.
> 5 votes

# Answer
# K, 12

```
{x@?&x:,//x}

```

.

```
k){x@?&x:,//x}((1;0);(2;0);(2;3))
1 2 2 3
k){x@?&x:,//x}(((4;5;8));((5;6;20));((1;20;500)))
4 5 8 5 6 20 1 20 500
k){x@?&x:,//x}(((1;0);(0;0);(0;0));((1;0);(1;2);(2;0));((2;0);(0;0);(0;0)))
1 1 1 2 2 2

```
> 4 votes

# Answer
**Perl 13, 14 char** dit: `p` count for one char

```
s/\D+|\b0/ /g

```

**usage:**

```
cat '[[1, 0], [2, 0], [2, 3]]' | perl -pe 's/\D+|\b0/ /g'

```
> 3 votes

# Answer
## Ruby, 38 characters

```
puts eval(gets).flatten.reject &:zero?

```

The numbers are printed separated by a line break.
> 2 votes

# Answer
### Golfscript 15

```
~{[]*}4*{},' '*

```

**Input**

Run from the command line, like so:

```
echo [[[1 0] [0 0] [0 0]] [[1 0] [1 2] [2 0]] [[2 0] [0 0] [0 0]]] | ruby golfscript.rb x.gs

```

(assumung that the `x.gs` file contains the code presented above).

*Note that there are no commas (`,`) when defining the arrays; that's Golfscript syntax*

**Output**

When the command described in the *Input* section is issued, the output is:

```
1 1 1 2 2 2

```
> 2 votes

# Answer
# Python 3, 49 chars

```
import re
print(*re.findall('[1-9]\d*',input()))

```

# Python 2, 58 chars

```
import re
print re.sub('\D[^1-9]*',' ',raw_input())[1:-1]

```
> 2 votes

# Answer
# Japt, 5 bytes

```
c f ¸

```

Test it

---

## Explanation

Implicit input of array `U`. Flatten the array with `c`. Filter it with `f` to remove the `0`s. Join it to a string using spaces with `¸`. Implicit output of resulting string.
> 2 votes

# Answer
# Java 10, 106 bytes

```
void c(Object i){for(var o:(Object[])i)try{System.out.print((int)o>0?o+" ":"");}catch(Exception e){c(o);}}

```

Input as nested `Object[]`, output printed to STDOUT.

Try it online.

---

**46 bytes**

```
s->s.replaceAll("[^0-9 ]","").replace(" 0","")

```

Input and output both as `String`.

Try it online.
> 2 votes

# Answer
## C, 45 chars

```
for(;s=strtok(s,"[], ");s=0)atoi(s)&&puts(s);

```

It assumes that the input is given in a modifiable memory area pointed by `s`.
> 1 votes

# Answer
## Python, 99 111 chars

```
def d(l):
    if list==type(l):return[y for x in l for y in d(x)]
    return[str(l)]*(l!=0)
print" ".join(d(input()))

```

Previous 99 char version - fails when lists with zeros only are included:

```
d=lambda l:list==type(l)and[y for x in l for y in d(x)]or[str(l)]*(l!=0)
print" ".join(d(input()))

```

`d(l)` recursively flattens the list `l`, while filtering zeros and converting numbers to strings.
> 1 votes

# Answer
### Scala, 42 chars

Tokenized the string by non digits and non-digit followed by zero.

```
print(readLine split"\\D|\\b0"mkString" ")

```
> 1 votes

# Answer
## Prolog (79)

It inputs the list as a term, so you need to put a '.' after the list in the input.

Actually does list flattening.

```
x([H|T]):-x(H),x(T).
x(0). x([]).
x(M):-write(M),put(32).
:-read(X),x(X),halt.

```
> 1 votes

# Answer
# APL (Dyalog), 4 bytes

```
0~⍨∊

```

Try it online!

`0~⍨` zeros removed from

the **ϵ**nlisted (flattened) data
> 1 votes

# Answer
# Stax, 2 bytes

```
$f

```

Run and debug it

`$` is flatten. `f` is filter out falsey values and print on separate lines.
> 1 votes

# Answer
# Vyxal `S`, 2 bytes

```
fꜝ

```

Try it Online!
> 1 votes

# Answer
### bash: 29 chars

```
l=$(echo "[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]]")
echo $l|tr -d '][,'|sed 's/\b0\b/ /g'
1           1   1 2 2   2

```

counting line 2 only withtout 'echo $l |'. Test for 3 samples:

```
  1    2    2 3
   4 5 8   5 6 20   1 20 500
   1               1    1 2  2     2

```
> 0 votes

# Answer
### Scala 147:

Working on real lists, not on strings:

```
def f[A](l:List[_]):List[_]=l match{
case Nil=>l
case(l:List[_])::s=>(f(l):::f(s))
case e::s=>e::f(s)}
def p(l:List[_])=f(l)filter(!=0)mkString " "

```

Now the testdata:

```
val l1 = List (List (1, 0), List (2, 0), List (2, 3))
val l2 = List (List (List (4, 5, 8)), List (List (5, 6, 20)), List (List (1, 20, 500)))
val l3 = List (List (List (1, 0), List (0, 0), List (0, 0)), List (List (1, 0), List (1, 2), List (2, 0)), List (List (2, 0), List (0, 0), List (0, 0)))
val l4 = List (l1, l2, l3)

scala> l4.map(p)
res94: List[String] = List(1 2 2 3, 4 5 8 5 6 20 1 20 500, 1 1 1 2 2 2)

scala> p(l4)
res95: String = 1 2 2 3 4 5 8 5 6 20 1 20 500 1 1 1 2 2 2

```
> 0 votes

# Answer
# Tcl, 47 bytes

```
proc D L {concat {*}[concat {*}[concat {*}$L]]}

```

Try it online!

Assuming 4-deep is something like `{{{{5}}}}`. As there is no example of such thing on test cases it may be something like `{{{5}}}`; if it is I can make my code shorter!

~~Tcl, 66 bytes
```
proc D L {lsearch -al -inl -not "[string map {\{ "" \} ""} $L]" 0}

```
Try it online!<br>~~
> 0 votes

# Answer
# Pyth, 5 bytes

```
jfT.n

```

**Test suite**
> 0 votes

# Answer
# , 29 bytes

```
function(l)(x=unlist(l))[!!x]

```

Try it online!

`unlist` converts the list to an `atomic` `vector` recursively, so we just need to filter out the zero elements.
> 0 votes

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

```
function(x){return(','+x+',').replace(/,(0,)*/g,' ')}

```

Try it online!
> 0 votes

# Answer
# Brachylog, 8 bytes

```
ċ∋↰|ℕ₁ẉ⊥

```

Try it online!

Takes input through the input variable and prints the output separated by newlines. Ordinarily I'd complain about the output format, but it actually saved me a byte in a way I might not have thought to otherwise--putting `ẉ⊥` on the end is shorter than wrapping it in `{}ᶠ`.

```
ċ           If the input is a list,
 ∋          pick some element of it
  ↰         and recur with it as the input.
   |        Otherwise, if the input
    ℕ₁      is a natural number,
      ẉ     print it with a trailing newline
       ⊥    then trigger backtracking.

```

If the list items aren't restricted to being non-negative integers:

# Brachylog, 11 bytes

```
ċ!∋↰|0!⊥|ẉ⊥

```

Try it online!
> 0 votes

# Answer
# PHP, 70 bytes

```
function($a){array_walk_recursive($a,function($a){echo$a?"$a ":'';});}

```

Try it online!

This isn't going to be the shortest (nor the longest), but figured it would be a chance to get to use `array_walk_recursive()`, which until today I can't think of ever having a use for it! At least it should be able to handle an arbitrary level deep nested lists.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 37 bytes

```
Flatten/*DeleteCases[0]/*StringRiffle

```

Try it online!
> 0 votes

---
Tags: code-golf
---