Question

How would I do this (C#) in F#

public class MyClass
{
    void Render(TextWriter textWriter)
    {
        Tag(() =>
                {
                    textWriter.WriteLine("line 1");
                    textWriter.WriteLine("line 2");
                });
        Tag(value =>
                {
                    textWriter.WriteLine("line 1");
                    textWriter.WriteLine(value);
                }, "a");
    }

    public void Tag(Action action)
    {
        action();
    }
    public void Tag<T>(Action<T> action, T t)
    {
    action(t);
    }
}
Was it helpful?

Solution

A multi-line lambda in F# is just

(fun args ->
    lots
    of
    code
    here
)

The whole code would be something like

open System.IO

type MyClass() as this =
    let Render(tw : TextWriter) =
        this.Tag(fun() ->
            tw.WriteLine("line1")
            tw.WriteLine("line2")
        )
        this.Tag(fun(value : string) ->
            tw.WriteLine("line1")
            tw.WriteLine(value)
        , "a"
        )
    member this.Tag(action) = 
        action()
    member this.Tag(action, x) =
        action(x)

assuming I made no transcription errors. (I used F# function types rather than Action delegates in the public interface.)

OTHER TIPS

If all you want to do is write multi-line lambdas, you can string several statements together using the semi-colon operator inside parenthesis. Example:

(fun () -> (write_line "line 1" ; write_line "line 2"))

and

(fun val -> (write_line "line 1" ; write_line val))

Though the second example I gave only works if val's type is string.

Caveat: I don't know the particulars of F#. I'm writing this from an Objective Caml background. The languages are very similar, but there may be some differences that make my suggestion slightly wrong. Also, I'm not at a machine with an ocaml or F# interpreter now so I can't check these snippets to ensure that they work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top