"defaultArg" is like getOrElse, and is available at the top level:

[link:research.microsoft.com]

1
2
3
4
5
let x = Some 3
let y = None
let z1 = defaultArg x 4
let z2 = defaultArg y 4
printfn "%d %d" z1 z2

The name reflects the fact that it's often use with optional arguments on methods, e.g.

1
2
3
4
5
6
7
8
9
10
type Foo() =
    static member SumArray(a : array<int>, ?startOffset : int) =
        let start = defaultArg startOffset 0
        let mutable sum = 0
        for i = start to a.Length-1 do
            sum <- sum + a.[ i ]
        sum
let a = [| 1; 2; 3; 4 |]
printfn "%d" (Foo.SumArray(a))
printfn "%d" (Foo.SumArray(a,2))
By on 7/23/2009 11:37 PM ()

Thanks. Yes, defaultArg is like getOrElse.

I imagine naming the function this way is an attempt to help communicate to people for a common use case. However, IMHO by doing so and not having it located in the OptionModule detracts from the abstraction and therefore all the other use cases.

By on 7/26/2009 6:27 PM ()

I wish there was a lazy operator for this (lazy in the same way as && and ||). That would be very useful for error handling, piping a series of default values, or using a complex computation as a default value.

1
2
3
4
let f x = getValue x |? failwith "not found"

let find x y = tryGet x |? tryGet y |? computeDefaultValue()

(that would be somewhat similar to the "or" operator we see in script languages, e.g. Python, PHP, Ruby...).

Laurent.

By on 7/24/2009 12:07 AM ()

Laurent, I was trying to something similar.

1
2
3
4
let t = 5
let s = [-1, 0, 1]
let f = Seq.tryFind (fun x -> x < 0) s
let g = Seq.tryFind ((=) 0) s

Instead of nested if-then-else statements

1
if Option.isSome f then Option.get f else if Option.isSome g then Option.get g else t

I basically want, using Haskell infix notation:

f `orElse` g `getOrElse` t

Or with the equivalent operators defined in my initial post

f |? g |?| t

I haven't investigated the laziness yet.

By on 7/26/2009 6:48 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper