FSharpx.Extras
FSharpx.Extras copied to clipboard
Option.getOrFailf - how to use this function?
Description
I am trying to use this function https://github.com/fsprojects/FSharpx.Extras/blob/0c34475e5e0a0217bae7c5e65271f4410e6c8bf4/src/FSharpx.Extras/ComputationExpressions/Monad.fs#L236-L239
but it seems to me that it does not do what I expect it to do... consider this snippet that fails to compile:
let x = Some 1
let _ = x |> Option.getOrFailF "asdf %b" true // error FS0001: Type mismatch. Expecting a 'int option -> 'a' but given a 'bool -> 'b'
let _ = x |> (Option.getOrFailF ("asdf %b" true)) // error FS0003: This value is not a function and cannot be applied
My question is - is this an expected behaviour of this function? How should I use it correctly?
I know there is a workaroud like that:
let _ = x |> Option.getOrFail (sprintf "asdf %b" true)
but I wanted to avoid writing sprintf, hence the question.
Pinging @sideeffffect
actually this could have never worked :( I'm removing it: https://github.com/fsprojects/FSharpx.Extras/pull/354 but thanks for trying it out!
I managed to draft working implementation:
> let x = Some 5
- let y : int option = None
- let inline getOrFailF fmt =
- let f s o =
- match o with
- | Some x -> x
- | None -> failwith s
- Printf.ksprintf f fmt
- ;;
val x : int option = Some 5
val y : int option = None
val inline getOrFailF : fmt:Printf.StringFormat<'a,('b option -> 'b)> -> 'a
> x |> getOrFailF "asdf %b" true;;
val it : int = 5
> y |> getOrFailF "asdf %b" true;;
System.Exception: asdf true
at [email protected](String s, FSharpOption`1 o) in c:\Repos\FSharpx.Extras\src\FSharpx.Extras\ComputationExpressions\Option.fs:line 0
at <StartupCode$FSI_0014>.$FSI_0014.main@()
Stopped due to error
@pmbanka Would you be still interested in having this in FSharpx.Extras?
@gdziadkiewicz I'm not involved in maintaining FSharpx, I was just a passerby :) So I guess this is a question for @sideeffffect.
FWIW, this looks to me like a nice useful helper that should go into the library.
I'm reluctant to add it in the form I proposed as it is misleading in terms of performance. It does the string printing thing in both the Some and None branches, and this is not what the user expects. I'm willing to accept an implementation that is not flawed in this way.
I think the only thing missing in the original implementation is the value passed to failwithf fmt None.
I suppose I’m not sure why you would want the format, as the failure case will always be None, won’t it?
Or it needs to take another parameter and pass it after fmt.