App2015
App2015

Reputation: 993

Choice type in F#

I'm getting some error with choice constructs, need help in fixing the code.

The error is

The 'if' expression needs to have type 'Choice' to satisfy context type requirements. It currently has type 'bool'.

let safeDiv num den : Choice<string, bool> = 
    if den = 0. then
        Choice1Of2 = "divide by zero"
    else 
        Choice2Of2 = (num/den)


printfn "%s" (safeDiv 15. 3.).Choice1Of2

Upvotes: 2

Views: 980

Answers (1)

ikh
ikh

Reputation: 10437

Your Choice has string and float, not string and bool.

let safeDiv num den : Choice<string, float> = 

Choice1Of2 and Choice2Of2 are constructors, so you should not use =. (Why do you use =? I cannot understand)

    if den = 0. then
        Choice1Of2 "divide by zero"
    else 
        Choice2Of2 (num / den)

Then, you should pattern-match to print the content of Choice.

match safeDiv 15. 3. with
    | Choice1Of2 msg -> printfn "%s" msg
    | Choice2Of2 x -> printfn "%f" x

(live example)

Upvotes: 8

Related Questions