hubFS: THE place for F#

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

string.Format problem

Last post 07-10-2008, 6:45 by Robert. 3 replies.
Sort Posts: Previous Next
  •  07-09-2008, 9:11 6340

    string.Format problem

    Hi,

    I am trying to evaluate the following in F# interactive version 1.9.4.17:

    > string.Format("{0} {1}", [| "abc" ; "def" |]);;
    System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
       at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
       at System.String.Format(IFormatProvider provider, String format, Object[] args)
       at <StartupCode$FSI_0132>.$FSI_0132._main()
    stopped due to error

    Can anyone point me what is wrong here?

    Thanks,
    dabd

  •  07-09-2008, 9:43 6341 in reply to 6340

    Re: string.Format problem

    The array argument is an array of ints not objects, hence the String.Format(string, obj) overload is called, not  String.Format(string, obj[])). Try this instead:


    string.Format("{0} {1}", Array.map box [|"abc"; "def"|])

    This would be the same in C#, btw. Also note that in F# "sprintf" gives you a properly typed formatted-printing function.

    Best regards,
      Stephan

  •  07-10-2008, 6:05 6351 in reply to 6341

    Re: string.Format problem

    I turned to using sprintf but I stumbled on another problem.

    I have a fairly big format string and I would like to do something like:

    #light
    let format_string = "let's say this is my big format string just to say %s"
    sprintf format_string "Hello!"

    But this is not correct.  How can I build a format string for sprintf?

    Thanks.
  •  07-10-2008, 6:45 6352 in reply to 6351

    Re: string.Format problem

    Because of some compiler magic that goes not the format string needs to be next to the printf function. The idiomatic F# solution to constraint is to create format functions:

    #light
    let myformater = sprintf "let's say this is my big format string just to say %s"
    let mystring = myformater "Hello!"


    But if you really want you string to be seperate you can use a type anontation:

    let (format_string:Printf.StringFormat<string->string>) = "let's say this is my big format string just to say %s"
    sprintf format_string "Hello!"


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