Ok so let's take the code, clean it up, and try to understand what it's doing
def generalOperationFuntion(operation: (Int, Int) => Int, opldentity:lnt) (functionToBeApplied: Int => Int)(from:Int,to:Int) : Int =
if from > to then opldentity else operation(functionToBeApplied(from),generalOperationFunction(operation,opIdentity)(functionToBeApplied)(from+1,to))
First, let's break the lines a bit
def generalOperationFuntion
(operation: (Int, Int) => Int, opldentity:lnt)
(functionToBeApplied: Int => Int)
(from:Int,to:Int) : Int =
if from > to
then opldentity
else operation(
functionToBeApplied(from),
generalOperationFunction
(operation, opIdentity)
(functionToBeApplied)
(from+1, to))
Ok, this is probably a bit much, but I'm on mobile, and it's impossible to read otherwise.
Next, lets use some shorter names
def generalOperationFuntion
(plus: (Int, Int) => Int, zero: lnt)
(f: Int => Int)
(from: Int, to: Int): Int =
if from > to
then zero
else plus(
f(from),
generalOperationFunction
(plus, zero)
(f)
(from+1, to))
Now we can think about what it's doing
in the base case, it returns 'zero'
in the recursive case, it it 'adds' the value of 'f' at the start of the range, and shrinks the range
For a lack of a better term, lets call this 'integration'. So, now we rename the function, and give it a final round of formatting.
def integrate
(plus: (Int, Int) => Int, zero: lnt)
(f: Int => Int)
(from: Int, to: Int): Int
=
if from > to
then zero
else plus(
f(from),
integrate(plus, zero)(f)(from+1, to))
Sorry, I think there is a few mistakes here. It should be
def generalOperationFuntion(operation: (Int, Int) => Int, opldentity:lnt)(functionToBeApplied: Int => Int)(from:Int,to:Int):Int =
if from > to then opldentity else operation(functionToBeApplied(from),generalOperationFunction(operation,opIdentity)(functionToBeApplied)(from+1,to))
The inner
generalOperationFunction(operation, opIdentity)
Was missing
Also, lnt instead of Int in a few places, and l instead of 1.
And it looks to me like there was some extra whitespace, and some missing =>
9
u/sebamestre Sep 25 '21 edited Sep 25 '21
Ok so let's take the code, clean it up, and try to understand what it's doing
First, let's break the lines a bit
Ok, this is probably a bit much, but I'm on mobile, and it's impossible to read otherwise.
Next, lets use some shorter names
Now we can think about what it's doing
For a lack of a better term, lets call this 'integration'. So, now we rename the function, and give it a final round of formatting.
5
u/Isvara Sep 26 '21
Looks like someone just learned about monoids.
1
u/[deleted] Sep 26 '21
which language is that?
0
u/[deleted] Sep 25 '21
[deleted] — view deleted comment