Home > database >  Implement Gaussian sum function in OCaml with lambda expression
Implement Gaussian sum function in OCaml with lambda expression

Time:11-21

I have to write a function sum that takes as first argument a value n. The second argument is a function f so that sum calculates the Gaussian sum.

In a second step, I have to implement thesum_gauss (int->int) using sum and a lambda expression.

This is my idea for the function sum:

let rec sum (n:int) (f:int->int) : int = 
  if n < 1 then 0 
  else sum (n-1) f   f n

And this is sum_gauss which throws an error:

let sum_gauss = sum ((i:int) -> fun (i:int) : int -> i)

The error is:

Line 1, characters 30-32:
Error: Syntax error: ')' expected
Line 1, characters 22-23:
  This '(' might be unmatched

I don't understand why this error is raised because every left bracket is matched by a right bracket.

CodePudding user response:

Rewriting with type inference cleaning things up:

let rec sum n f = 
  if n < 1 then 0 
  else sum (n-1) f   f n

If you wish to add all number from 1 to n. you need to pass the number and the function to sum_gauss as separate arguments.

let sum_gauss n = sum n (fun x -> x)

Of course, fun x -> x is really just Fun.id.

let sum_gauss n = sum n Fun.id

If you feel like being extra clever and you're already using the Fun module you can use Fun.flip to pass Fun.id as the second argument of sum and elide n from the definition entirely. The fact that sum is not polymorphic avoids weak typing issues with partial application.

let gauss_sum = Fun.(flip sum id)
  • Related