Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiline lambda expressions in f#?

Tags:

lambda

f#

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);
    }
}
like image 968
Simon Avatar asked May 02 '09 06:05

Simon


People also ask

Can lambda functions be multiple lines?

No, you cannot write multiple lines lambda in Python. The lambda functions can have only one expression.

How do you write multiline lambda in Python?

No, you can't write multiline lambda in Python because the lambda functions can have only one expression. The creator of the Python programming language – Guido van Rossum, answered this question in one of his blogs. where he said that it's theoretically possible, but the solution is not a Pythonic way to do that.

How do you write multiple statements in lambda expression?

Unlike an expression lambda, a statement lambda can contain multiple statements separated by semicolons. delegate void ModifyInt(int input); ModifyInt addOneAndTellMe = x => { int result = x + 1; Console. WriteLine(result); };


1 Answers

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.)

like image 73
Brian Avatar answered Oct 13 '22 02:10

Brian