Bash, 5454 48 bytes
-6 bytes by adapting Dominic van Essen's output-prevention trick
echo "trap 'echo \$s'printf EXIT":|:
((s+=p<$1?$1-2*p:$1))
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, luckily Bash has just the trick. I expect one of the golfing languages that will output by default at the end of the program would do best here.
Explanation
Example output for 3 concatenated with output for 10 (the concatenated program outputs 7):
trap 'echo $s' EXIT:|:
((s+=p<3?3-2*p:3))
p=3
trap 'echo $s'echo EXIT$s:|:
((s+=p<10?10-2*p:10))
p=10
echo $s
trap:|:runsprevents anyechoonly at the end of the program, and only oncefrom a previous fragment from outputtingsis the sum value so far (implicitly 0 at the start of the program)pis 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.