Shadow
Shadow

Reputation: 2478

How to pass string concatenation to function in f#

How to pass string concatenation operator (I do not want to use ^) to function?

If I try to create variable: let x = (+) compiler says x is of type int -> int -> int. How can I annotate x so it works on strings?

Upvotes: 0

Views: 92

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243096

UPDATED QUESTION: To answer your updated question - the + operator is generic and uses static member constraints to work on any type that supports it. This gets lost if you use it in a function or assign it to variable. The one way to keep this property is to define an inline function.

let x1 = (+)               // Type constrained, because it's not a function
let x2 a b = (+)           // Type constrained, because it's not `inline`
let inline x3 = (+)        // Error: only functions can be `inline`
let inline x4 a b = a + b  // Works and you can use `x4` with strings and ints

ORIGINAL ANSWER: There must be something else going on in your situation that you are not showing in your question. If you just open a new F# script file, the following works:

let funInt (f:int -> int -> int) = f 1 2
let funStr (f:string -> string -> string) = f "hi" "there"

funInt (+)
funStr (+)

Now, I'm not sure what else you have in your code that is causing the error. One possibility I can think of is if you re-defined the + operator - if you have a new definition that is not inline, you'll get the error you describe:

let funInt (f:int -> int -> int) = f 1 2
let funStr (f:string -> string -> string) = f "hi" "there"

let (+) a b = a + b

funInt (+)
funStr (+)

Can you post a minimal reproducible example that illustrates the issue?

Upvotes: 2

Related Questions