hubFS: THE place for F#

. . . are you on The Hub?
Welcome to hubFS: THE place for F# Sign in | Join | Help
in Search

Function Return Types

Last post 07-01-2008, 5:21 by Robert. 3 replies.
Sort Posts: Previous Next
  •  07-01-2008, 4:39 6256

    Function Return Types

    Hi

    I am a newbie to F#, I am trying to create a function abc that takes an integer parameter and returns a float value. How do i declare the function. ? If i attempt as following , I  get the error as "This expression has type  float but is here used with type  int  "

    let quad x:int = 2.0

    Can any one please help ?
    Can any one also specify a good tutorial to start F# ?

    Thanks n Regards
    Anu Viswan


  •  07-01-2008, 5:03 6257 in reply to 6256

    Re: Function Return Types

    You need to learn to let go of type declartions, a lot of the time in F# you have no need for them, you could just write:

    let quad x = 2.0

    The function will return type float because 2.0 is a float. The parameter x is not used so it will be a generic parameter 'a. If you want to take an int and return a float you just need to explicitly convert your int to a float and the compiler will infer that the parameters an int:

    let quad x = float x * 2.0

    Chris Smith's F# in twenty minutes is probably the best tutorial for F# beginners:
    http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx

    "Foundations of F#" would probably help too if you were looking to buy a book.

    Cheers,
    Rob

    Robert Pickering
    http://strangelights.com
  •  07-01-2008, 5:10 6258 in reply to 6257

    Re: Function Return Types

    Hi Rob

    Thanks for reply, But my purpose was different.
    I had a function which takes an input X of type ABC.
    ABC is user declared type which contains a 1 float and 2 integers.

    type ABC=
    {
    a:int;
    b:int;
    c:float;
    }


    I want to pass an instance of this type to a function and which returns a type int.

    let quad x:ABC= (x.a + x.b)

    But when i attempt this i get error. Can you please help in same ??

    Thanks n Regards
    Anu Viswan







  •  07-01-2008, 5:21 6259 in reply to 6258

    Re: Function Return Types

    This too is okay without type annotations, because the type of record types can be infered from their members (if the members are unquie within the scope):

    type ABC=
      { a:int;
        b:int;
        c:float; }
    let quad x = (x.a + x.b)


    But if you do need a type annotation for a parameter you need to put brackets round it, without brackets its the return type of the function that your are declaring:

    let quad (x:ABC) = (x.a + x.b)

    Cheers,
    Rob

    Robert Pickering
    http://strangelights.com
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems