tags:

views:

90

answers:

1

I'm trying to implement the following with OCaml for a homework assignment:

g(n) = y if n = x else f(n)

so, for example

if f(n) = n+1, x = 7, y=42, then g(1) = 2, but g(7) = 42

I've got:

# let update f x y = f(x) = y;;
val update : ('a -> 'b) -> 'a -> 'b -> bool = < fun>

but I just don't know the syntax I should use in order to make it return a function instead of a boolean value.

I'm not asking for someone to solve the problem, but if someone could post some code that takes in a function, manipulates it, and returns it, I'd appreciate it.

+1  A: 

Not sure I understand your homework -- are you sure you just don't want to call f(n) instead of returning it?

But, some examples -- a function that returns another function

(* given a number, return a function that takes an int 
   and returns integer + number *)
let adder n = 
    let f x = n+x in
    f

Note that the type it returns is a function:

# adder 10;;
- : int -> int = <fun>
# let g = adder 10;;
val g : int -> int = <fun>
# g 20;;
- : int = 30

Basically, to return a function, you define the function and just return it.

Let's say you want to take a function and return a function that returns double the value:

let doubler f = 
    let g x = 2 * (f x) in 
    g

# let f x = x + 1;;
val f : int -> int = <fun>
# let g = doubler f;;
val g : int -> int = <fun>
# g 10;;
- : int = 22
brool
Thanks a lot! Between this and the professor replying to my email, I was able to figure it out.I'll post my solution after the homework deadline in case someone from the class ends up at this page via google.