[Question]
  [
## Background
Roman numeral is a simple number system with the following properties:
* Each symbol in the system maps to a specific value. (e.g. `I = 1, V = 5, X = 10, C = 100`)
* The value of a Roman numeral can be evaluated as follows:
	+ First, find all occurrences of adjacent pairs of symbols where a strictly smaller-valued symbol comes first (e.g. `IV`, `XC`). Each such pair is evaluated as the backward difference of two values (e.g. `IV = 5 - 1 = 4`).
	+ Then, interpret the remaining symbols as-is and sum all values in it.
	
	```
	MMCMXCIV = M + M + CM + XC + IV
	         = 1000 + 1000 + (1000 - 100) + (100 - 10) + (5 - 1)
	         = 2994
	
	```
## Task
Your job is to write a function/program \$F\$ that takes a positive integer \$n\$ and generates a code fragment \$F(n)\$ (not necessarily in the same language). The outputted code fragments must have the following properties:
* \$F(n)\$ as a full program must output the number \$n\$.
* \$F(a)+\!\!\!+\,F(b)\$ as a program (where \$+\!\!+\$ means concatenation) must output \$a+b\$ if \$a≥b\$, \$b−a\$ otherwise.
* This must extend to any number of code fragments emitted by your program in the way that \$b−a\$ cases take precedence (think of an arithmetic expression with `+`s and `-`s, but the two sides of `-`s are flipped and it has higher precedence than `+`).
	+ You do not need to consider the cases where three consecutive input numbers are strictly increasing (the equivalent arithmetic expression has two consecutive `-`s).
Your score is the byte count of \$F\$. Shortest code in bytes wins.
## Example
If \$F(10)\$ outputs the code fragment `ABC`, and \$F(3)\$ outputs the code fragment `xyz`:
* The program `ABC` should output 10.
* The program `xyz` should output 3.
* The program `ABCxyz` should output 13.
* The program `xyzABC` should output 7.
* The program `ABCABCABC` should output 30.
* The program `ABCABCxyzxyzABCxyzxyzABC` should output 40, since
```
[10, 10, 3, 3, 10, 3, 3, 10] => 10 + 10 + 3 + (10-3) + 3 + (10-3) = 40
```
Additionally, if \$F(8)\$ outputs the code fragment `****`:
* The program `ABC****xyz` should output `10 + 8 + 3 = 21`.
* The program `****ABCxyz` should output `(10-8) + 3 = 5`.
* The program `xyz********ABC` should output `(8-3) + (10-8) = 7`.
* You do not need to consider the program `xyz****ABC`, which contains three consecutive strictly increasing numbers (3, 8, 10).
  
[Answer]
# Bash, ~~54~~ 48 bytes
*-6 bytes by adapting Dominic van Essen's output-prevention trick*
```
printf ":|:
((s+=p<$1?$1-2*p:$1))
p=$1
echo \$s"
```
This assumes the program must not have any excess output, which turns out to be one of the tricker parts. I expect one of the golfing languages that will output by default at the end of the program would do best here.
[Try it online!](https://tio.run/##TY7LCsIwEEX38xWXMItGKTRmU6rFH3HTR2oLkoRWsKB@e0xQ0dU9c@fATNssYzgbm0ncg58nex0gqkdFWbZsa39gdWSV7za@YiUl@ZoVmW50OPEiwpNu43QxmE3T4zJZs0fvCOhcb2ohIg1uxorJgv/WX4FTcBbPg1eZ9N5ZE6ONXyHv8DYEpTqogjSpApo0IkdKA/QvUlfGfYmPViIhvQA "Bash – Try It Online")
## Explanation
Example output for `3` concatenated with output for `10` (the concatenated program outputs `7`):
```
:|:
((s+=p<3?3-2*p:3))
p=3
echo $s:|:
((s+=p<10?10-2*p:10))
p=10
echo $s
```
* `:|:` prevents any `echo` from a previous fragment from outputting
* `s` is the sum value so far (implicitly 0 at the start of the program)
* `p` is the previous value
Each fragment assumes that the current value is not less than the next value, and thus adds it to the sum. It also checks whether the previous fragment was wrong to assume this (ie. the previous value was less than the current value), and if so corrects the sum by subtracting double the previous value.
[Answer]
# [R](https://www.r-project.org/), ~~65~~ 57 bytes
```
cat("d=e=F;F=c(",scan(),",F);a=sum(F*(-1)^(F<c(e,0)));a")
```
[Try it online!](https://tio.run/##zY9Ra8IwEMff8ymO@JIbFVoiDFr7mk8xhBhPLLhE0qv67bs2wqYbbFQZ@HIkd7nf/5fY986ykpuaalOZ2imZtc56hZnMDFa2brt3ZV7UvMCVMkunKMsRh4HEvsiFSNtvXqKYQej40DFsQ4TGj6ewBV2KuwOEvuX7cAKmlqHhMl2ZSvBEG@AAkVpiONrY2PWewMCa@ETkgazbXdZi50UcwrBK1LFXQpEn@pff0IHfzcRPiv4O0dMZQ64ei6LzgRxD8YqT1SYYPPjjT91UrrT14mm0/x/759v@Aw "R – Try It Online")
**How it works (original version)**
For an example input of 3, the output is:
```
d=0;F=c(F, 3 );a=sum(F*(-1)^(F<c(F[-1],0)));a
```
(note: no trailing newline)
What do the different bits do?
* `d=0` = appends to the last code fragment (if any). This has the effect of changing the final `a` (output the contents of `a`) to `ad=0` (assign zero to variable `ad`), and thereby supresses output from all non-final code fragments.
* `F=c(F, 3 )` = append the input value to the list `F`. `F` is a shortcut in [R](https://www.r-project.org/) for `FALSE`, so it's initialized to zero. So, after all the code fragments are pasted together, `F` will contain all the input integers, followed by zero.
* `a=sum(F*(-1)^(F<c(F[-1],0)))` = calculate the sum of all the input integers, switching the sign of any that are immediately followed by a larger value. Luckily the last value is zero, so this won't happen to the final input integer. Assign the answer to variable `a`.
* `a` = Finally, output the answer `a` (but if there's a following code fragment, this'll get changed to `ad=0` and nothing output yet... see the start)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~26~~ 24 bytes
Full program. Prompts for number from stdin, and prints program to stdout.
```
'{⍺←+/⊢×¯1*2</,∘0⋄⍺,⍵}'⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@fWpaY86htwqPePq6Cosy8EiC7@lHfVCClrq7wqLtFAcJ51Lu1lutRRxtYuncXEOk86p0KEv2vDhZom6Ct/6hr0eHph9YbahnZ6Os86phhANQPUbm1Vh2o@b8bxKZHXc2Petc86t1yaL3xo7aJQBuCg5yBZIiHZ/B/sCsUHJ2cgWrdFAwNuEAuBPG5IA5UqKisAksZQ2SAXJhMQVF@elFiLlAWqFwHJAFWARXGVAVUoQMyGL8qkFlQTKRKkLlQs5HZWHWDwhSOQN6yUFB41DtXQUlLSSGzWCEvv0QhUQGoLzNFITMlNa8kMy0ztUghOSOxKDG5JLUIYiayIdidhayCiJBBUU58YKJoQzeDVP3oWgA "APL (Dyalog Unicode) – Try It Online") (slightly modified version for ease of use)
The generating program simply prepends a special string to the left of the input number (or numbers, actually).
The special string is an anonymous ambivalent (infix/prefix) lambda.
Compound programs will consist of numbers separated by this lambda, with an additional lambda on the far left.
With infix usage, the lambda amounts to simple concatenation.
With prefix usage, the lambda evaluates Roman numbers.
APL evaluates from right to left, so a compound statement will simply concatenate number values until finally the list is evaluated as a Roman number.
The lambda is as follows:
`{`…`}` dfn; arguments are `⍺` (left, optional) and `⍵` (right):
 `⍺←` if the left argument is undefined (i.e. we are being called monadically, as a prefix lambda), give the following tacit function value to it:
 `+/` the sum of…
 `⊢` the argument array…
 `×` times (element-wise)…
 `¯1*` negative one raised to the power of (element-wise)…
 `2</` the pair-wise less-than of…
 `,∘0` the argument prepended to a zero
 `⋄` now, with the supplied or the default `⍺` evaluate:
  `⍺,⍵` with a supplied left argument the concatenation of the arguments
  `⍺,⍵` with the default argument the tacit function applied to the ravel (flattened ― a no-op) right argument
[Answer]
# [JavaScript (V8)](https://v8.dev/), 66 bytes
```
n=>`t=this;s=~~t.s-(t.p<${n}&&2*p)+(p=${n}),{get x(){print(s)}}.x`
```
[Try it online!](https://tio.run/##XY9hb4MgEIa/8yvuw1KhtUTnF5OO/RFnUmNhtWmByMU0MfavO4E2cyOBu@d97zi4NEPj2r6zuB/KWYlZi88jCjx37uDE44Hc7Sly@/E26mmzed9atqNWeGLp@C0R7pSNtu80Usemid@PcyRF84wx8oJiyUlrtENA6dCBgIpUeVanpCr8kWcp@F348E8o/mYvt1zY5@XTDncFOSg1qQlRpgf6OxeMivMZjASWFa3WnOTyIu/wW2OpYvxiOk2ThIWq@IvkSyewC1Vr2TdHPsmrRAm4BrcGG0AOzfXZNc0/ "JavaScript (V8) – Try It Online")
The core idea is putting the `print()` behind a getter function. If the `.x` property is accessed it will print the total `s`. This is placed at the end of the generated code so that it accesses `.x` on the last iteration and when concatenated it becomes `.xt=this` (does not access `.x`).
[Answer]
# [Zsh](https://www.zsh.org/), ~~34~~ 32 bytes
```
<<<"((s+=p<$1?$1-2*p:$1));p=$1;"
```
~~[Try it online](https://tio.run/##bU7BToQwFLzzFRNspF0lkeVCdkG/wJM3jQeEV9pkt5BtSVaN344toO7BpOlMpzNv3odVU0eGi8@pLMuYc3tTDSXLHliWbjfDjmW3Q@UvK8Q@nr4i2Z/gyDrwCEiyuyRAniwPLCTHqnsliMj/4EcvVm@Bi1iBYraIeXqoOoOzKvSJfdO3VMUsAON@ZbCziCPvu0Jtre4MXA85msbp3oT4Su2LfK3m2GJ2dDjg2So4pS38qXGsnfo3ivQRcok9EaGlt7Gb93KKMJy0cdT@uv231EYHuvMR9z6QJYdUQuL@eruMGS1dNlGjejDOIbmAEJGYom8 "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##bU7BToQwFLzzFRNspNWQyHIhC@gXePKm8YDwSpvsFrItyarx27EF1D2YNJl505k378OquSfDxedcVVXMub2tx4plDyxLdzfjnmVClGPNsjKevyI5nODIOvAISLK7JECerANWkmPTvRJE5H/woxebt8BFrECxWMSyPVSdwVkd@kTZDh3VMQvAuD8Y7CziyPuu0FirewM3QE6mdXowIb5R@yJf6yW2mh0dDni2Ck5pC/8aHBun/o0ifYRcY09E6Oht6pe7nCKMJ20cdb9u/y210YHufcS9j2TJIZWQuL/erWsmS5dN1KoBjHNILiBEJOboGw "Zsh – Try It Online")
Adapted from [Vitrivius's Bash answer](https://codegolf.stackexchange.com/a/220435/86147) (go upvote it too!), shorted considerably by taking advantage of Zsh's math function functionality (Math functions are defined to output the result of the last math expression, which means we don't need to worry about supressing output.)
[Answer]
# [Perl 5](https://www.perl.org/) (`-lp`), ~~39~~ 35 bytes
-4 bytes thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)
```
$_='}{$\-=2*$p*($p<'."$_)-(\$p=$_)"
```
* `-lp` switch (enable line ending processing;assume loop like -n but print line also, like sed)
* generated code starts with `}{` : which closes the loop block and start a new block which is executed after the loop
* `-=`, `$p=..` rewriting so that affectation is executed after operation and comparison
[Try it online!](https://tio.run/##K0gtyjH9r5JsW6jxXyXeVr22WiVG19ZIS6VAS0OlwEZdT0klXlNXI0alwBbIUPqvaa3irGebWpaYo5JszcUFUm6rpOLMpaSXUAA0SkE3pyBVQV3FWT3hv6EBlyGXocG//IKSzPy84v9AKQA "Perl 5 – Try It Online")
[Answer]
# Java, 696 bytes
```
n->"import java.util.*;import java.io.*;import java.util.jar.*;interface Main{List<Integer>l=new ArrayList();static void main(String[]a)throws Exception{var z=Main.class.getPackageName();for(var e:System.getProperty(\"java.class.path\").split(System.getProperty(\"path.separator\"))){if(!e.endsWith(\".jar\")){var b=new File(e+File.separatorChar+z);var d=b.listFiles();Arrays.sort(d);for(var f:d){var n=f.getName();if(n.endsWith(\".class\")){Class.forName(n.substring(0,n.length()-6));}}}}int s=0;for(int i=0;i<l.size();i++)s+=l.get(i)-(i>0&&l.get(i)>l.get(i-1)?l.get(i-1)*2:0);System.out.print(s);}}\nclass _"+new java.util.Date().getTime()+"_"+System.nanoTime()+"{static{Main.l.add("+n+");}}//"
```
The `Main` interface has a static `List` field which all the generated classes add an integer to in their static initializer. The main method attempts to load all the classes in the package to run their static initializers. `F(a)` will return different values each time since it tries to make the class names unique using the current time, so `F(a) + F(a)` cannot be shortened by using a variable to store the result of `F(a)`.
[Generator](https://tio.run/##jVJRb9MwEH7frzB5mOyFeh1IPDRNERpMQgKENCQeKELXxEnduXZku93aqL@9nJ2UlqlI@MWX83fffd/lFrCGwaJ82DermZIFKRQ4Rz6D1KS9IHj6vPPg8VobWZIlvtJ7b6Wuf/wkYGvHOmw4CyTkKy8Vr1a68NJo/lH7uz4ed2UTUuV7PZgkctkY60@KrrLTlDTPEhGzABvS2gtbQSGi2vaTdH6MnUQt7ETlWjySd9bCJuQpy/6pH5ifW/PoyIenQjRBY7sGS7Z5YOVxHLwW/isUD1CLL7AUyFYZSwNKjO43zotlRFjTCOs3dJpEqV1pA34@TRh3jZKenkUHCHeiAQveWAQz1sqKvhBc6NJ9l36OoGA6PEVxs2jvTipBRRquY/ntHGy6ZVmAlfmMK7QfEA5Vx3k47nCatDyaqEZlR6vzKkjrPaIE/ZeCaChquI3WsD5CNXermYvjpMOXmiuha6xggzeMZTs8@KeIy4exYYglxnKsuJPb2ChNmUtzFXpTyQZUToaXl4fPSR8MbtjbY3j1ajRkWT9Os/K8wfaeutBwqrsl/pWkYUzHvXkPHvsFjm8yWEwThPQcGrQ5ZNtuWdq4AYpDWVKkSpNAfn2d7A@rnv1Z@m6ZiMEBQtOoDb0ZsvRc/Pps@F@Ik27PbCtNTf@8u9jtfwM)
[Generated Program](https://tio.run/##7ZVda9swFIbv9yu8XBSpXlR/x47rjFE6GHRj0ItdjFEUW3aUOrKRlHSJ2W9PJSUjZZTdbbmRwfj4@D06H3qwlniDx8vqcb@nq77j0lkqB1pL2qLL/KWLdn84jGaJuXYzSXiNS@J8xpQNd1TI60/K1xA@awtGnpwPnOOt9gOYC4klLZ1NRytnpfTgXnLKmu8/MJQL3j0J5/ZnSXpJOzZsMHd2hV4VlS0WAjVEfsXlI27IF7wiarW640CryPR@KyRZGQXvesLlFoxMpYfIHsvFCCLRt1SC17RagATpMcey4yMI4UBr8JYgwirxjcoFGOl@1QdT1tw09pG2BBBXP06xNwvM3R3Mtawq5qhVjWuFUPWaSQgk1BxBdSq/nlaHZVlR67KO3akC2Mv8phVdwY3pSUUbIUNiPRdmjMB7x1BLWKP0cJxAmP9Sl9ohRxSeSadtqmx63SJBdyaN60LhFq3ODCgcAzrzLi5@v86OxtiH70/mZTD1YH4cZLeWqFfpJRA64RtTp/PgJ34c@lHsx0ESPSRREvpZGARpnGTBcOBgMJvbIlxVwPd08NWVRdGi@A9RzIIjinGWplHmhRZFi@L5UVR3nL6CYmhJtCT@TxIzL5okiSXRknh2Ev1gkmb2eLYonh/FwJt4sf0pWhLPTmIU@pPQkmhJPDuJcZgE6V@O5/3@GQ)
[Answer]
# Python 3.7.3 (outputs Python 3.7.3), 174 bytes
```
import sys;print("""R=%s
class A():
 def __del__(s):print(a)
if"a"in locals():
 if"p"in locals()and p<R:a-=p+p-R
 else:a+=R
if"v"not in locals():v=A();a=R
p=R"""%sys.argv[1])
```
More readable version of the code:
```
import sys
print("""
number = %s
class PrintOnExit():
   def __del__(self):
      # This object will only be destroyed when the interpreter exits
      print(result)
if "result" in locals():
   if "previous" in locals() and previous < number:
       result -= previous
       result += number - previous
   else:
       result += number
if "print_on_destroy" not in locals():
    print_on_destroy = PrintOnExit()
    result = number
previous = number
""" % sys.argv[1])
```
```
[Answer]
# [Julia](http://julialang.org/) REPL, 50 bytes
adapted from [Dominic's answer](https://codegolf.stackexchange.com/a/220436/98541)
```
x->"L=0;L=[L;$x];a=sum(L.*(-1).^[diff(L).>0;0]);a"
```
[Try it online!](https://tio.run/##XU5BCsMgELzvKyT0oKUVJZeA2GNP9gViQRoDhjQpMS35faq2oaTCujszy@y0z85bPi9nuczHU6EkE0pqJXazEVaG5x0rusdHTuhV175psCL0xAQzRNhieYy@n7oenzFnhMAPlhHB5MIUkEQaNGfmALpMH2cHlKpM7Y8ot9OqVhGnufrK2SvTmTFgAJphROkg8n3uAVB8t6F2MUE7@JiK4iTEZElZs25RXtgwyWHLuJft8MVNlj7sGNxnI7q6vgZY3g "Julia 1.0 – Try It Online")
# [Julia](http://julialang.org/), 68 bytes
Basically the same with a `print` that erases the previous line (doesn't work in TIO)
```
x->"L=0;L=[L;$x];print(\"\\r\\e[K\",sum(L.*(-1).^[diff(L).>0;0]));L"
```
[Try it online!](https://tio.run/##XY7RCsIgFIbvz1PI6EJjibKbQNZlN9kTqMFoDhxri7lib7/UiliCnvP/nx7/9tG5is/LsVzm3SGTJROyVFJsZiPuo@snrDOtR62tOuks948blnSLd5zQi6pd02BJ6IEJZggRMlvSm67HR8wZIfCTRVAwWT95VCIFijOTgyriwVmO4i5i@TOKdfel@6Bjv//gNCvZyTFgAJphRPFD5PpUPaCwrkNtQ4J2cCEVxRGEZJF8s65VurBy4oS3Y59Vh892qui9Gr19EwK2rwGWFw "Julia 1.0 – Try It Online")
[Answer]
## JavaScript (ES6), generates [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
f=
n=>`⎚⊞υＩ${n}ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Explanation:
```
⎚
```
Clears the canvas of the previous output.
```
⊞υＩ${n}
```
Takes the stringified value, casts it back to integer, and pushes it to the predefined empty list.
```
ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι
```
Compares each element of the list with the next element, negating the element if it is smaller, then prints the final sum.
Example: F(10) is `⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺…υ¹υκ±ιι`, while F(3) is `⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. The last example is therefore `⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ3ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υＩ10ＩΣＥυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. [Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHXfPOt77fs9LQAEicW/x@z9LzrY/62h817Dy389DyR427gNx1PUCia@q5XYc2ngMKU6zLmG6ahpH7/v8HAA "Charcoal – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~17~~ ~~16~~ ~~15~~ 14 bytes
```
⁶,y“_< ×ḤƲɼ+ ©
```
[Try it online!](https://tio.run/##y0rNyan8//9R4zadykcNc@JtFA5Pf7hjybFNJ/doKxxa@ahh7v/D7Y@a1rg93NkS9v9/tKGBjgIIG4MRMisWAA "Jelly – Try It Online") The TIO version has an extra closing quote which can be omitted, but that breaks the footer, so I left it in; that's why it displays 15 bytes.
## Explanation
```
⁶,y“_< ×ḤƲɼ+ ©   Main monadic link
⁶                " "
 ,               [" ", n]
  y              In the following string, replace " " with n
   “             {
                   Value implicitly starts at 0
                   Register implicitly starts at 0
    _              Subtract from the current value
          ɼ          the result of applying this to the register
         Ʋ           (
     <                 Is it smaller than n? (no -> 0, yes -> 1)
       ×               Multiply that by
        Ḥ                twice the register
         Ʋ           )
           +       Add n to the current value
             ©       and copy n to the register
                 }
```
[Answer]
### Python 3, 120 bytes
```
lambda n:f"""import atexit as a
try:
 z[-1]*=1-2*(z[-1]<{n})
except:
 z=[];a.register(lambda:print(sum(z)))
z+=[{n}]
"""
```
The lambda function returns the code snippet using a f-string. In the snippet, `z` is a list of the "Roman Numerals". In the `try` block, the code negates the last number in `z` if it is less than the current number `n`. If `z` doesn't exist yet an exception is thrown and caught by the `except`, where `z` is initialized to an empty list and a lambda function is registered with `atexit`. Lastly, the new number as appended to `z`. When the interpreter exits, the registered lambda print the sum of `z`.
]