簡體   English   中英

F#Subtype Disriminated Unions

[英]F# Subtype Discriminated Unions

我有這樣的DU:

type Food =
| Beer
| Bacon
| Apple
| Cherry

如果食物是水果,我想給DU添加一個特征來標記。 我首先想到的是這樣的事情:

type NonFruit = NonFruit
type Fruit = Fruit

type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit

然后像這樣的方法:

讓fruitChecker(myFood:Food)=將myFood與|匹配 :? NonFruit - >“不”| :? 水果 - >“是”

但是編譯器對我大喊大叫:

“食物”類型沒有任何正確的子類型,不能用作來源

我是否錯誤地接近了這個問題?

謝謝

或者,使用活動模式: https//msdn.microsoft.com/en-us/library/dd233248.aspx

type Food =
| Beer
| Bacon
| Apple
| Cherry

let (|NonFruit|Fruit|) =
    function
    | Beer | Bacon -> NonFruit
    | Apple | Cherry -> Fruit

let fruitChecker = function | NonFruit -> "No" | Fruit -> "Yes"

[Beer;Bacon;Apple;Cherry] |> List.iter(fun x -> printfn "%s" (fruitChecker x))

打印:

No
No
Yes
Yes

鏈接: https//dotnetfiddle.net/oRYDs6

你應該簡單地添加一個函數。 如果要使其“接近”類型,請將其設為靜態成員:

type Food =
   | Beer
   | Bacon
   | Apple
   | Cherry
   static member IsFruit = function Beer | Bacon -> false | Apple | Cherry -> true

將DU案例視為構造函數 - 將啤酒廠的名稱傳遞給Beer構造函數是有意義的,但無論它是否為水果都是靜態質量,在那里是不合適的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM