Interpolated strings in F#
Asked Answered
M

3

7

I am trying to use the Entity Framework Core interpolated SQL query function in F# which requires a FormattableString. However to my surprise it doesn't function as I cannot find a way to convert a regular F# string to that type. I figured just doing what you do in C# would work but it doesn't. Here is the code I currently have:

let fromDbUser (u : Entity.User) = 
    {
        name = u.Name
        age = u.Age
        phone = u.Phone
    }

let mname = "Foo" 

let ctx = new Entity.DatabaseContext()
ctx.User.FromSqlInterpolated($"Select * FROM User Where name = {mname};") 
|> Seq.map(fromDbUser)
|> printfn "%A"

Running that block of code yields a compile error:

This token is reserved for future use

I have been trying to google around but I was unable to find any way to get this to work, any help would be most appreciated!

Moonmoonbeam answered 7/2, 2020 at 20:57 Comment(0)
S
11

When this was asked, F# didn't have string interpolation.

Today though, there is an RFC for it that is merged in in F# 5.0 allowing string interpolation in F#.


The error was because the $ symbol is reserved (for 6 years+ as of writing), and will probably be used for string interpolation when it is added.

Sapp answered 7/2, 2020 at 21:49 Comment(0)
E
4

As Dave pointed out, interpolation isn't implemented yet. But for methods that absolutely require an FormattableString or an IFormattable, you can use FormattableStringFactory.Create

let query (sql: FormattableString)  = 
    printfn "%s" (sql.ToString(null, null))

let mname = "Foo"         
let fstr = FormattableStringFactory.Create("Select * FROM User Where name = {0};", mname)

query fstr
Etymology answered 8/2, 2020 at 12:20 Comment(0)
C
2

It's available from F# 5.0.

> let mname = "Foo" ;;
val mname : string = "Foo"

> let str = $"Select * FROM User Where name = {mname};" ;;
val str : string = "Select * FROM User Where name = Foo;"

Check this out. https://learn.microsoft.com/en-us/dotnet/fsharp/whats-new/fsharp-50#string-interpolation

Coulisse answered 17/11, 2020 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.