[Question]
  [
Assume we want to shift an array like it is done in [the 2048 game](https://gabrielecirulli.github.io/2048/): if we have two equal consecutive elements in array, merge them into twice the value element.
Shift must return a new array, where every pair of consecutive equal elements is replaced with their sum, and pairs should not intersect. 
Shifting is performed only once, so we don't need to merge resulting values again.
Notice that if we have 3 consecutive equal elements, we have to sum rightmost ones, so for example, `[2, 2, 2]` should become `[2, 4]`, not `[4, 2]`.
The task is to write shortest function which takes an array and returns a shifted array.
You may assume that all integers will be strictly positive.
Examples: 
```
[] -> []
[2, 2, 4, 4] -> [4, 8]
[2, 2, 2, 4, 4, 8] -> [2, 4, 8, 8]
[2, 2, 2, 2] -> [4, 4]
[4, 4, 2, 8, 8, 2] -> [8, 2, 16, 2]
[1024, 1024, 512, 512, 256, 256] -> [2048, 1024, 512]
[3, 3, 3, 1, 1, 7, 5, 5, 5, 5] -> [3, 6, 2, 7, 10, 10]
```
I am also very interested in solution using reduce :)
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10 9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œg+2/€UF
```
**[TryItOnline](http://jelly.tryitonline.net/#code=xZJnKzIv4oKsVUY&input=&args=WzIsIDIsIDIsIDQsIDQsIDhd)** or **[run all test cases](http://jelly.tryitonline.net/#code=xZJnKzIv4oKsVUYKxbzDh-KCrEfigqxq4oG3O-KBt8Kk&input=&args=W1tdLCBbMiwgMiwgMl0sIFsyLCAyLCA0LCA0XSwgWzIsIDIsIDIsIDQsIDQsIDhdLCBbMiwgMiwgMiwgMl0sIFs0LCA0LCAyLCA4LCA4LCAyXSwgWzEwMjQsIDEwMjQsIDUxMiwgNTEyLCAyNTYsIDI1Nl0sIFszLCAzLCAzLCAxLCAxLCA3LCA1LCA1LCA1LCA1XV0)**
### How?
```
Œg+2/€UF - Main link: a                 e.g. [2,2,2,4,4,8]
Œg       - group runs of equal elements      [[2,2,2],[4,4],[8]]
   2/€   - pairwise reduce for each with
  +      -     addition                      [[4,2],[8],[8]]
      U  - reverse (vectorises)              [[2,4],[8],[8]]
       F - flatten list                      [2,4,8,8]
      
   
```
[Answer]
## Haskell, ~~47~~ ~~57~~ 50 bytes
```
e#l|a:b<-l,e==a= -2*a:b|1<2=e:l
map abs.foldr(#)[]
```
Uses `reduce` (or `fold` as it is called in Haskell, here a right-fold `foldr`). Usage example: `map abs.foldr(#)[] $ [2,2,2,4,4,8]` -> `[2,4,8,8]`.
Edit: +10 bytes to make it work for unsorted arrays, too. Merged numbers are inserted as negative values to prevent a second merge. They are corrected by a final `map abs`.
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 158 96
```
{({}<>)<>}<>{(({}<>)<><(({})<<>({}<>)>)>)({}[{}]<(())>){((<{}{}>))}{}{{}(<({}{})>)}{}({}<>)<>}<>
```
[Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fTw-KTw-fTw-eygoe308Pik8PjwoKHt9KTw8Pih7fTw-KT4pPikoe31be31dPCgoKSk-KXsoKDx7fXt9PikpfXt9e3t9KDwoe317fSk-KX17fSh7fTw-KTw-fTw-&input=MiAyIDIgNCA0IDg)
**Explanation:** 
1 Reverse the list (moving everything to the other stack, but that doesn't matter) 
```
{({}<>)<>}<>
{        }   #keep moving numbers until you hit the 0s from an empty stack
 ({}<>)      #pop a number and push it on the other stack
       <>    #go back to the original stack
          <> #after everything has moved, switch stacks
```
2 Do steps 3-6 until there is nothing left on this stack:
```
{                                                                                         }
```
3 Duplicate the top two elements (2 3 -> 2 3 2 3)
```
(({}<>)<><(({})<<>({}<>)>)>)
(({}<>)<>                   #put the top number on the other stack and back on the very top
         <(({})             #put the next number on top after:
               <<>({}<>)>   #copying the original top number back to the first stack
                         )>)
```
4 Put a 1 on top if the top two are equal, a 0 otherwise (from the wiki) 
```
({}[{}]<(())>){((<{}{}>))}{}
```
5 If the top two were equal (non-zero on the top) add the next two and push the result
```
{{}(<({}{})>)}{}
{            }   #skip this if there is a 0 on top
 {}              #pop the 1
   (<      >)    #push a 0 after:
     ({}{})      #pop 2 numbers, add them together and push them back on 
              {} #pop off the 0
```
6 Move the top element to the other stack
```
({}<>)<>
```
7 Switch to the other stack and print implicitly
```
<>
```
[Answer]
## Python, 61 bytes
```
def f(l):b=l[-2:-1]==l[-1:];return l and f(l[:~b])+[l[-1]<<b]
```
The Boolean `b` checks whether the last two elements should collapse by checking that they are equal in a way that's safe for lists of length 1 or 0. The last element if then appended with a multiplier of `1` for equal or `2` for unequal. It's appended to the recursive result on the list with that many elements chopped off the end. Thanks to Dennis for 1 byte!
[Answer]
# PHP, 116 Bytes
```
<?$r=[];for($c=count($a=$_GET[a]);$c-=$x;)array_unshift($r,(1+($x=$a[--$c]==$a[$c-1]))*$a[$c]);echo json_encode($r);
```
or
```
<?$r=[];for($c=count($a=$_GET[a]);$c--;)$r[]=$a[$c]==$a[$c-1]?2*$a[$c--]:$a[$c];echo json_encode(array_reverse($r));
```
-4 Bytes if the output can be an array `print_r` instead of 'json\_encode`
176 Bytes to solve this with a Regex
```
echo preg_replace_callback("#(\d+)(,\\1)+#",function($m){if(($c=substr_count($m[0],$m[1]))%2)$r=$m[1];$r.=str_repeat(",".$m[1]*2,$c/2);return trim($r,",");},join(",",$_GET[a]));
```
[Answer]
# GNU sed, 41 38 37
Includes +1 for -r  
-3 Thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)  
-1 Thanks to [seshoumara](https://codegolf.stackexchange.com/users/59010/seshoumara)
```
:
s,(.*)(1+) \2\b,\1!\2\2!,
t
y,!, ,
```
Input and output are space separated strings in unary ([based on this consensus](http://meta.codegolf.stackexchange.com/a/5349/57100)).
[Try it online!](http://sed.tryitonline.net/#code=OgpzLCguKikoMSspIFwyXGIsXDEhXDJcMiEsCnQKcywhLCAsZw&input=MTEgMTEgMTExMSAxMTExCjExIDExIDExIDExMTEgMTExMSAxMTExMTExMQoxMSAxMSAxMSAxMQ&args=LXI)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 32
```
\d+
$*
r`\b\1 (1+)\b
$1$1
1+
$.&
```
`r` on line 3 activates right-to-left regex matching. And this means that the `\1` reference needs to come before the `(1+)` capturing group that it references.
[Try it online.](http://retina.tryitonline.net/#code=XGQrCiQqCnJgXGJcMSAoMSspXGIKJDEkMQoxKwokLiY&input=MiAyIDQgNAoyIDIgMiA0IDQgOAoyIDIgMiAyCjIgMiAy)
[Answer]
# Perl, 41 bytes
Includes +1 for `-p`
Give input sequence on STDIN:
```
shift2048.pl <<< "2 2 2 4 4 8 2"
```
`shift2048.pl`:
```
#!/usr/bin/perl -p
s/.*\K\b(\d+) \1\b/2*$1.A/e&&redo;y/A//d
```
[Answer]
# JavaScript (ES6), 68 bytes
```
f=a=>a.reduceRight((p,c)=>(t=p[0],p.splice(0,c==t,c==t?c+t:c),p),[])
    
console.log([
  [],
  [2, 2, 4, 4],
  [2, 2, 2, 4, 4, 8],
  [2, 2, 2, 2],
  [4, 4, 2, 8, 8, 2],
  [1024, 1024, 512, 512, 256, 256],
  [3, 3, 3, 1, 1, 7, 5, 5, 5, 5],
].map(f))
```
[Answer]
## Perl, 43 + 1 (`-p`) = 44 bytes
Ton Hospel came up with 41 bytes [answer](https://codegolf.stackexchange.com/a/95438/55508), check it out!
 *-4 thanks to @Ton Hospel!* 
**Edit** : added `\b`, as without it it was failing on input like `24 4` on which the output would have been `28`.
```
$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge
```
Run with `-p` flag : 
```
perl -pe '$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge' <<< "2 2 2 4 4"
```
  
I don't see another way than using `reverse` twice to right-fold (as just `s/(\d+) \1/$1*2/ge` would left-fold, i.e `2 2 2` would become `4 2` instead of `2 4`). So 14 bytes lost thanks to `reverse`... Still I think there must be another (better) way (it's perl after all!), let me know if you find it! 
[Answer]
# Perl 5.10, ~~61~~ 50 bytes (~~49~~ + 1 for flag)
Thanks to [Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for saving 11 bytes!
Regex-free solution, with `-a` flag:
```
@a=($F[-1]-$b?$b:2*pop@F,@a)while$b=pop@F;say"@a"
```
[Try here!](https://ideone.com/1tKnMa)
[Answer]
# JavaScript (ES6), ~~68...64~~ 58 bytes
```
a=>(g=p=>(x=a.pop())|p?p?[...g(p^x?x:!(p*=2)),p]:g(x):a)()
```
[Try it online!](https://tio.run/##hY7NCsIwEITvPkW9ZaVGG/tHIfZBSoVQa1HELFakB9@9ZhMRsbaGyVx25ts9qbtqq@sRb8uL3tf9QfZKblkj0XgnFUeNDOCBOeYF57xhuOvyLpszXEgB4GOZNayDTAGDvtKXVp9rftYNO7CiBPCm32rlFeXsqyZ8zyg0GgNQzczTkeqrTYEBgKpunk4CxJ/d4aDqVgoH/gmgamojQUyBb0KwFobgPArEy0QUWyOevX4dph@pAWXje06BVWJSb7mbiGLmsT0lIRb9sn8C "JavaScript (Node.js) – Try It Online")
### Commented
```
a => (                  // a[] = input array
  g = p =>              // g is a recursive function taking p = previous value
    (x = a.pop())       //   extract the last entry x from a[]
    | p ?               //   if either x or p is a positive integer:
      p ?               //     if p is a positive integer:
        [               //       update the output:
          ...g(         //         do a recursive call:
            p ^ x ?     //           if p is not equal to x:
              x         //             set new_p = x
            :           //           else:
              !(p *= 2) //             double p and set new_p = false
          ),            //         end of recursive call
          p             //         append p
        ]               //       end of output update
      :                 //     else:
        g(x)            //       do a simple recursive call with new_p = x
    :                   //   else:
      a                 //     stop recursion and return a[], which is guaranteed
                        //     to be an empty array at this point
)()                     // initial call to g with p undefined
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 26 bytes
```
D¥__X¸«DgL*ê¥X¸«£vy2ôO})í˜
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RMKlX19YwrjCq0RnTCrDqsKlWMK4wqvCo3Z5MsO0T30pw63LnA&input=WzIsIDIsIDIsIDQsIDQsIDhd)
**Generalized steps**
1. Reduce by subtraction to find where consecutive elements differ
2. Reduce by subtraction over the indices of those places to find the length of consecutive elements
3. Split input into chunks of those lengths
4. Split chunks into pairs
5. Sum each pair
6. Reverse each summed chunk
7. Flatten to 1-dimensional list
[Answer]
# Mathematica, 53 bytes
```
Join@@(Reverse[Plus@@@#~Partition~UpTo@2]&/@Split@#)&
```
# Explanation
```
Split@#
```
Split the input into sublists consisting of runs of identical elements. i.e. `{2, 2, 2, 4, 8, 8}` becomes `{{2, 2, 2}, {4}, {8, 8}}`.
```
#~Partition~UpTo@2
```
Partition each of the sublist into partitions length at most 2. i.e. `{{2, 2, 2}, {4}, {8, 8}}` becomes `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}`.
```
Plus@@@
```
Total each partition. i.e. `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}` becomes `{{4, 2}, {4}, {16}}`.
```
Reverse
```
Reverse the results because Mathematica's `Partition` command goes from left to right, but we want the partitions to be in other direction. i.e. `{{4, 2}, {4}, {16}}` becomes `{{2, 4}, {4}, {16}}`.
```
Join@@
```
Flatten the result. i.e. `{{2, 4}, {4}, {16}}` becomes `{2, 4, 4, 16}`.
[Answer]
# Haskell, 56 bytes
```
g(a:b:r)|a==b=a+b:g r|l<-b:r=a:g l
g x=x
r=reverse
r.g.r
```
[Answer]
## Java 7, 133 bytes
```
Object f(java.util.ArrayList<Long>a){for(int i=a.size();i-->1;)if(a.get(i)==a.get(i-1)){a.remove(i--);a.set(i,a.get(i)*2);}return a;}
```
Input is an ArrayList, and it just loops backwards, removing and doubling where necessary.
```
Object f(java.util.ArrayList<Long>a){
    for(int i=a.size();i-->1;)
        if(a.get(i)==a.get(i-1)){
            a.remove(i--);
            a.set(i,a.get(i)*2);
        }
    return a;
}
```
[Answer]
# Perl, 37 bytes
Includes +4 for `-0n`
Run with the input as separate lines on STDIN:
```
perl -M5.010 shift2048.pl
2
2
2
4
4
8
2
^D
```
shift2048.pl:
```
#!/usr/bin/perl -0n
s/\b(\d+
)(\1|)$//&&do$0|say$1+$2
```
[Answer]
# PHP, ~~86 100 99~~ 94 bytes
```
for($r=[];$v=+($p=array_pop)($a=&$argv);)array_unshift($r,end($a)-$v?$v:2*$p($a));print_r($r);
```
requires PHP 7.0; takes values from command line arguments.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/8e345e910aa2254c49fbdcbecb2fbcbb35e3dbb3).
[Answer]
# Julia 205 bytes
```
t(x)=Val{x}
s(x)=t(x)()
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))
g()=[]
g{a}(::t(a))=[a]
g{a}(::t(a),B...)=[a;g(B...)]
g{a}(::t(a),::t(a),B...)=[2a;g(B...)]
K(A)=g(s.(A)...)
H(A)=(K^s(length(A)))(A)
```
Function to be called is `H`
eg `H([1,2,2,4,8,2,])`
This is in no way the shortest way do this in julia.
But it is so cool, that I wanted to share it anyway.
* `t(a)` is a value-type, representing the value (a).
* `s(a)` is an instance of that value type
* `g` is a function that dispatches on the difference values (using the value types) and numbers of its parameters. And that is cool
* `K` just wraps `g` so that
Extra cool part:
```
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))
```
This defines the `^` operator to apply to functions.
So that `K^s(2)(X)` is same as `K(K(X))`
so `H` is just calling `K` on `K` a bunch of times -- enough times to certainly collapse any nested case
This can be done much much shorter, but this way is just so fun.
[Answer]
## PowerShell v2+, 81 bytes
```
param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count..0]
```
Takes input as an explicit array `$n`, reverses it `$n[$n.count..0]`, `-join`s the elements together with a comma, then regex `-replace`s a matching digit pair with the first element, a `*2`, and surrounded in parens. Pipes that result (which for input `@(2,2,4,4)` will look like `(4*2),(2*2)`) over to `iex` (short for `Invoke-Expression` and similar to `eval`), which converts the multiplication into actual numbers. Stores the resulting array into `$b`, encapsulates that in parens to place it on the pipeline, then reverses `$b` with `[$b.count..0]`. Leaves the resulting elements on the pipeline, and output is implicit.
---
### Test Cases
***NB--*** In PowerShell, the concept of "returning" an empty array is meaningless -- it's converted to `$null` as soon as it leaves scope -- and so it is the equivalent of returning nothing, which is what is done here in the first example (after some wickedly verbose errors). Additionally, the output here is space-separated, as that's the default separator for stringified arrays.
```
PS C:\Tools\Scripts\golfing> @(),@(2,2,4,4),@(2,2,2,4,4,8),@(2,2,2,2),@(4,4,2,8,8,2),@(1024,1024,512,512,256,256),@(3,3,3,1,1,7,5,5,5,5)|%{"$_ --> "+(.\2048-like-array-shift.ps1 $_)}
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:67
+   param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+                                                                   ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Cannot index into a null array.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:13
+   param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
 --> 
2 2 4 4 --> 4 8
2 2 2 4 4 8 --> 2 4 8 8
2 2 2 2 --> 4 4
4 4 2 8 8 2 --> 8 2 16 2
1024 1024 512 512 256 256 --> 2048 1024 512
3 3 3 1 1 7 5 5 5 5 --> 3 6 2 7 10 10
```
[Answer]
# Javascript - 103 bytes
```
v=a=>{l=a.length-1;for(i=0;i<l;i++)a[l-i]==a[l-1-i]?(a[l-i-1]=a[l-i]*2,a.splice(l-i,1)):a=a;return a}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 60 bytes
```
{({}<>)<>}<>{(({}<>)<>[({})]){((<{}>))}{}{({}<>{})(<>)}{}}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjutbGTtPGDkhWa8A40UCGZqwmUMCmutZOU7O2uhaiECisAVQB5AM5//8bKYCgCRBaAAA "Brain-Flak – Try It Online")
### Explanation:
```
{({}<>)<>}<>   Reverse stack
{   While input exists
  (
    ({}<>)   Push copy of last element to the other stack
    <>[({})] And subtract a copy of the next element
  )   Push the difference
  {   If the difference is not 0
    ((<{}>)) Push two zeroes
  }{}  Pop a zero
  {   If the next element is not zero, i.e the identical element
    ({}<>{})  Add the element to the copy of the previous element
    (<>)      Push a zero
  }{}    Pop the zero
}<>  End loop and switch to output stack
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes
```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HPXsNHXUsPrQAyHnU1PepdYVQDZGoAxYBsW81DK3RiHnXMAAr9T3vUNuFRb9@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MUHvWu4UpTMNIBIRMggnOgfB0FC0whI2QhIwgfKgNUD0YgIUMDI6AQhDQ1NIISRqZmYAKowFgHigzByByoAo4A "APL (Dyalog Unicode) – Try It Online")
Fully tacit version of the previous solution, thanks to Adám.
### How it works
```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽  ⍝ Right argument: V, vector to reduce by 2048 rules
                   ⌽  ⍝ Reverse V to get RV
                ,\∘   ⍝ Prefixes of RV
         ⌽(  =)¨      ⍝ For each prefix, test if each element equals last element
           ⊥⍨         ⍝   and count trailing ones
                      ⍝   (one-based index of each item within runs)
       2|             ⍝ Modulo 2
    ⌽⊂⍨               ⍝ Partition RV at ones of the above
 1⊥¨                  ⍝ Sum of each chunk
⌽                     ⍝ Reverse back
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 bytes
```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRz15t/UMrqh/1bn3U1fSod4VRTfWjrqVABlDE9lFXM1ABkFV7aIVODIiGcv@nPWqb8Ki371HfVE9/oKpD640ftU0E8oKDnIFkiIdn8P80hUe9a7jSFIx0QMgEiOAcKF9HwQJTyAhZyAjCh8oA1YMRSMjQwAgoBCFNDY2ghJGpGZgAKjDWgSJDMDIHqoAjAA "APL (Dyalog Unicode) – Try It Online")
A full program. Link is to function version for easier testing.
### How it works
```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕
                         ⎕  ⍝ Take input
                        ⌽   ⍝ Reverse
    {                  }    ⍝ Apply the anonymous function...
                    ,\⍵     ⍝   Prefixes
          {       }¨        ⍝   For each prefix,
             ⍵=⊃⌽⍵          ⍝     Evaluate if each element is equal to last
           ⊥⍨               ⍝     and count trailing ones
                            ⍝     (one-based index of each item within runs)
        2|                  ⍝   Take modulo 2
     ⍵⊂⍨                    ⍝   Partition the input array at 1's of the above
 +/¨                        ⍝ Sum each group
⌽                           ⍝ Reverse back
```
[Answer]
# Python 2, 94 bytes
```
def f(a,r=[]):
 while a:
    if len(a)>1and a[-1]==a[-2]:a.pop();a[-1]*=2
    r=[a.pop()]+r
 print r
```
[**Try it online**](https://repl.it/DpVo)
[Answer]
## Racket 166 bytes
```
(λ(l)(let g((l(reverse l))(o '()))(cond[(null? l)o][(=(length l)1)(cons(car l)o)]
[(=(car l)(second l))(g(drop l 2)(cons(* 2(car l))o))][(g(cdr l)(cons(car l)o))])))
```
Ungolfed: 
```
(define f
  (λ (lst)
    (let loop ((lst (reverse lst)) 
               (nl '()))
      (cond                            ; conditions: 
        [(null? lst)                   ; original list empty, return new list;
               nl]
        [(= (length lst) 1)            ; single item left, add it to new list
              (cons (first lst) nl)]
        [(= (first lst) (second lst))  ; first & second items equal, add double to new list
              (loop (drop lst 2) 
                    (cons (* 2 (first lst)) nl))]
        [else                          ; else just move first item to new list
              (loop (drop lst 1) 
                    (cons (first lst) nl))]  
        ))))
```
Testing:
```
(f '[])
(f '[2 2 4 4]) 
(f '[2 2 2 4 4 8]) 
(f '[2 2 2 2]) 
(f '[4 4 2 8 8 2])
(f '[1024 1024 512 512 256 256]) 
(f '[3 3 3 1 1 7 5 5 5 5])
(f '[3 3 3 1 1 7 5 5 5 5 5])
```
Output:
```
'()
'(4 8)
'(2 4 8 8)
'(4 4)
'(8 2 16 2)
'(2048 1024 512)
'(3 6 2 7 10 10)
'(3 6 2 7 5 10 10)
```
[Answer]
# [Julia 0.6](http://julialang.org/), ~~73~~ 82 Bytes
```
f(l)=l==[]?[]:foldr((x,y)->y[]==x?vcat(2x,y[2:end]):vcat(x,y),[l[end]],l[1:end-1])
```
[Try it online!](https://tio.run/##XZDRisMgEEXf/YqBfVEwUG2ahoDpc79hmIeybSCL2CV1l/brs6OmIaxcBzn3Xgb8@vHjpZnnQXrlvHNIJ6RuuPvrJOVTv1TVv5Cce55@Py9RWkZou1u4kuoySRmNHhMi7dEkszKk5nh7xAc4QHEOEUl/QNUDkkCrgVWz3pDf7WosXkKLXUj7L2Q37ZqNUrIluLHbDE2TkECzs5wq82DsMuyhyWPduKvbTYp7ew1FJuvIfNW7xW6Tlx1TN10SJMRwnyDCGCD/iAA@39MYog8yguthkFEpwd82/wE "Julia 0.6 – Try It Online")
Use right fold to build list from back to front (one could also use fold left and reverse the list at the beginning and end).
If the head of the current list is not equal to the next element to prepend, then just prepend it.
Else remove the head of the list (sounds kind of cruel) and prepend the element times 2.
*Example*
```
f([3,3,3,1,1,7,5,5,5,5]) 
returns a new list:
[3,6,2,7,10,10]
```
[Answer]
# Mathematica, 51 bytes
```
Abs[#//.{Longest@a___,x_/;x>0,x_,b___}:>{a,-2x,b}]&
```
---
`{Longest@a___,x_/;x>0,x_,b___}` matches a list containing two consecutive identical positive numbers and transform these two numbers into `-2x`. `Longest` forces the matches to happen as late as possible. 
The process is illustrated step by step:
```
   {3, 3, 3, 1, 1, 7, 5, 5, 5, 5}
-> {3, 3, 3, 1, 1, 7, 5, 5, -10}
-> {3, 3, 3, 1, 1, 7, -10, -10}
-> {3, 3, 3, -2, 7, -10, -10}
-> {3, -6, -2, 7, -10, -10}
-> {3, 6, 2, 7, 10, 10}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
ò¦ ®ò2n)mxÃc
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=8qYgrvIybilteMNj&input=LW1RClsKICBbXSwKICBbMiwgMiwgNCwgNF0sCiAgWzIsIDIsIDIsIDQsIDQsIDhdLAogIFsyLCAyLCAyLCAyXSwKICBbNCwgNCwgMiwgOCwgOCwgMl0sCiAgWzEwMjQsIDEwMjQsIDUxMiwgNTEyLCAyNTYsIDI1Nl0sCiAgWzMsIDMsIDMsIDEsIDEsIDcsIDUsIDUsIDUsIDVdCl0=)
### Unpacked & How it works
```
Uò!= mZ{Zò2n)mx} c
Uò!=    Partition the input array where two adjacent values are different
        i.e. Split into arrays of equal values
mZ{     Map the following function...
Zò2n)     Split into arrays of length 2, counting from the end
          e.g. [2,2,2,2,2] => [[2], [2,2], [2,2]]
mx        Map `Array.sum` over it
}
c       Flatten the result
```
Got some idea from [Jonathan Allan's Jelly solution](https://codegolf.stackexchange.com/a/95413/78410).
[Answer]
# [Common Lisp](http://www.clisp.org/), 143 bytes
```
(defun e(l)(if(<(length l)1)'()(if(eq(car l)(cadr l))(cons(*(car l)2)(e(cddr l)))(cons(car l)(e(cdr l))))))
(defun f(l)(reverse(e(reverse l))))
```
[Try it online!](https://tio.run/##bU/BDsIgDL37Fc0SY/EkuOkO/syygS5BNmF63K/PFvDgMl5Ky3sPWlrbh3FZsNPm7UCjFdgbvKHV7j49wAopDhg5/cK28cRQ6jhTMbiAx0wrgRrbLklZyxeYTzStXe5luJfXH@2DJkeukus3z@h7h0EAmsE/mwkmKOZm3hcQ@B1WSQIa8P@oQEEJ5QYbeag3FbVi2amgJqwVeVIlxK2SKoaqLhwr3xkYknCFKoE/9wU "Common Lisp – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous prefix lambda.
```
{∊((⊃⍴⍨2|≢),+⍨⍴⍨∘⌊2÷⍨≢)¨⍵⊂⍨2≠/0,⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR5eGRp1RzaPORZqP2iY/6mrW0X7Uu@JR7xYQ2THjUU@X0eHtIDZQwSGg@NZHXU1ArtGjzgX6BjpAfu3/tEdtEx719j3qm@rpDzTg0HrjR20TgbzgIGcgGeLhGfw/TeFR7xquNAUjHRAyASI4B8rXUbBAFjICciDCQI4FGIGEDA2MgEIQ0tTQCEoYmZqBCaACYx0oMgQjc6AKOAIA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` dfn; `⍵` is right argument
 `0,⍵` prepend a zero to the argument
 `2≠/` pairwise inequality mask
 `⍵⊂⍨` use that to partition (true means begin new partition here) the argument
 `(`…`)¨` apply the following tacit function to each run of equal numbers:
  `≢` the length of the run
  `2÷⍨` let 2 divide that
  `⌊` floor that
  `∘` then
  `⍴⍨` use it to **r**eshape…
  `+⍨` the doubled (lit. addition selfie) run
  `(`…`),` append that to the following:
   `≢` the length of the run
   `2|` division remainder when divided by two (1 for odd length runs, 0 for even length runs)
   `⊃⍴⍨` use that to reshape the first element of the run
 `∊` **e**nlist (flatten)
]