Function which returns itself

Posted by Juliet on Stack Overflow See other posts from Stack Overflow or by Juliet
Published on 2010-04-21T00:10:45Z Indexed on 2010/04/21 0:13 UTC
Read the original article Hit count: 148

Filed under:

As a purely academic exercise (read "because I have no life"), I'm trying to write a function f which accepts another function g, executes g for its side effect, and returns itself.

So I have this:

let rec f g x =
    ignore(g x)
    fun y -> f g y

F# complains:

      fun y -> f g y;;
  -------------^^^^^

C:\Users\Juliet\AppData\Local\Temp\stdin(8,14): error FS0001: Type mismatch. Expecting a
    'a    
but given a
    'b -> 'a    
The resulting type would be infinite when unifying ''a' and ''b -> 'a'

If it works the way I intend, then I could write:

let printer = f (printfn "%s")
printer("this")("is")("so")("useless")("its")("awesome!")
// prints:
//    this
//    is
//    so
//    useless
//    its
//    awesome

Is it possible to write a function like this?

© Stack Overflow or respective owner

Related posts about F#