Scott Nimrod
Scott Nimrod

Reputation: 11595

How can I execute function returning type from discriminated union

I am not sure how to write this statement.

let dealPlayer() = Hit(Two; Spades)

Error This expression was expected to have type

type Suit = | Spades
            | Diamonds
            | Clubs
            | Hearts

type Face = |Two | Three | Four | Five 
            | Six | Seven | Eight | Nine | Ten
            | Jack | Queen | King | Ace

type Card = {Face: Face; Suit: Suit}

type Deal = | Hand of Card * Card
            | Hit of Card

let dealPlayer() = Hit(Two; Spades)

I'm still new to F#. Please help me.

Upvotes: 1

Views: 36

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233125

Assuming that you want dealPlayer to always return the hard-coded two of spades, it's done like this:

let dealPlayer () = Hit { Face = Two; Suit = Spades }

The dealPlayer function has the inferred type unit -> Deal.

Card is a record type, so you'll need to to use a record expression to create a value of that type. That's the { Face = Two; Suit = Spades } part.

The Hit part is the case constructor for the Hit case of Deal.

Upvotes: 3

Related Questions