Search code examples
castingf#type-safety

F# casting an int


This is a quite trivial thing but I am really struggling to get this to work. I want to cast the results of sqrt n where n is of type int64 and finally pass that to a function that takes an int but I am really struggling to get a decent solution of it, this is the way I came up with but this is hideous and I can't believe that something that is so trivial to do in for example C# should be so hard in F#.

n 
|> float 
|> sqrt 
|> int 
|> function

Solution

  • This is F# - if you don't have what you want, write a function. For instance:

    let inline sqrttoint n =
        (int (sqrt (float n)))
    
    n |> sqrttoint |> function
    

    On top of that it works on anything that can cast to float.

    The main issue of C# vs F# is that you are used to C# where numeric types are auto-promoted whereas F# wants you to care about the type of most everything and changes in type need to be more explicit.