1

Ok I am very new to F# so maybe this has been well explained in the textbooks but why F# function with curried arguments cannot have optional parameter. For instance function Fun1 doesn't compile whereas the other two functions compile fine. I want to know what's reason for having this constraint on optional parameter? And is there, if any, way to get around this constraint?

type TestOptionalParameter = 
    member x.Fun1 (a: int) (?b : bool) = 
        if defaultArg b true then a else 2 * a
    member x.Fun2 (?b : bool) = 
        if defaultArg b true then "yes" else "no"
    member x.Fun3 (a: int, ?b : bool) = 
        if defaultArg b true then a else 2 * a
ildjarn
  • 62,044
  • 9
  • 127
  • 211
dragonfly02
  • 3,403
  • 32
  • 55

2 Answers2

3

Let's look at an example if it would be allowed:

let top = TestOptionalParameter()
let fn1 = top.Fun1 4

What in this case would be the value of fn1: function of type (bool -> int) or the result of method Fun1 call with default second parameter value (false)?

I think because of this ambiguity functions with curried arguments are not allowed to have optional parameters

Petr
  • 4,280
  • 1
  • 19
  • 15
2

I guess that this is a design decision taken in F# since it is possible to have optional parameters in curried functions in OCaml.

Optional parameters in F# are implemented through the option type, assuming that you have a function of (for example) int -> bool option -> int, even if you have some special annotation for an optional parameter version, e.g. int -> ?bool -> int I think it could become more difficult to reason about how these functions behave in actual usage, especially in the presence of partial application because the number of arguments won't always match what's implied by the type signature.

This answer could be of interest to you with respect to some of the downsides of this approach as implemented in OCaml: https://stackoverflow.com/a/23703761/5438433

There is a suggestion to implement optional parameters in let bound functions on the F# Language Design User Voice site: https://fslang.uservoice.com/forums/245727-f-language/suggestions/5663215-optional-and-named-parameters-on-let-bindings-on-m, it's not clear to me whether, if accepted, this would implement the same behaviour as currently available for optional parameters on types or implement the OCaml-like behaviour for curried arguments.

Community
  • 1
  • 1
TheInnerLight
  • 12,034
  • 1
  • 29
  • 52
  • Of all the answers regarding this question I particularly like this one as it does more than simply answering the question. – dragonfly02 Jan 02 '16 at 20:17