Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: difference between type defined with and without parenthesis

Tags:

f#

What's the difference between type Something() and type Something in F#?

Why this snippet referenced in ASP.NET Core 1.0 F# project works:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup() = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0

but this fails:

open System
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http

type Startup = 
    member this.Configure(app: IApplicationBuilder) =
      app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))

[<EntryPoint>]
let main argv = 
    let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build()
    host.Run()
    printfn "Server finished!"
    0
like image 899
Alexander Mischenko Avatar asked Mar 12 '23 18:03

Alexander Mischenko


1 Answers

You can see the difference by typing it in the F# Interactive:

type Parens() =
    member this.add10 x = x + 10

type NoParens =
    member this.add10 x = x + 10;;

Output:

type Parens =
  class
    new : unit -> Parens
    member add10 : x:int -> int
  end
type NoParens =
  class
    member add10 : x:int -> int
  end

The second class doesn't have a constructor defined. Something the compiler shouldn't allow, but does for some reason. It doesnt generate an automatic constructor like C#.

For more info check the F# for fun and profit pages on classes and interfaces. Also check out this StackOverflow post

And for future reference, when in doubt, open the F# interactive, type the two things you want to see the difference between, and compare the output. It is a powerful tool and you should use it.

like image 92
asibahi Avatar answered May 10 '23 06:05

asibahi