Cogito Ergo Sum
Cogito Ergo Sum

Reputation: 810

F#: How exactly is ToString supposed to be used?

I am learning F# but I just don't understand how I am supposed to use ToString. Below are a few attempts. The syntax errors are saying it is expecting type string but that it is actually type uint -> string. So it doens't actually appear to be invoking a function? Could this be explained? This seems like such a simple thing to do but I can't figure it out.

open System
open System.IO
open FSharp.Data

[<EntryPoint>]
let main (args: string[]) =
    let htmlPage = HtmlDocument.Load("https://scrapethissite.com/")

    printfn  "%s" htmlPage.ToString // This causes a syntax error
    
    htmlPage.ToString
    |> (fun x -> printfn "%s" x) // This also causes a syntax error

    0

Upvotes: 3

Views: 1797

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

.ToString is a method, not a value. In F# every method and every function has a parameter. In fact, that's how functions differ from values (and methods from properties): by having a parameter.

Unlike in C#, F# methods and functions cannot be parameterless. If there is nothing meaningful that you'd want to pass to the method, that method would still have one parameter of type unit. See how this is visible in the error message? unit -> string is the type.

To call such method, you have to pass it the parameter. The sole value of type unit is denoted (). So to call the method you should do:

    htmlPage.ToString ()
    |> printfn "%s"

Your first example is a bit more complicated. The following would not work:

printfn "%s" htmlPage.ToString ()

Why? Because according to F# syntax this looks like calling printfn and passing it three parameters: first "%s", then htmlPage.ToString, and finally (). To get the correct order of calls you have to use parentheses:

printfn "%s" (htmlPage.ToString ())

And finally, general piece of advice: when possible try to avoid methods and classes in F# code. Most things can be done with functions. In this particular case, the ToString methods can be replaced with the equivalent function string:

printfn "%s" (string htmlPage)

Upvotes: 4

Related Questions