我有多個數據定義,作爲一個簡單的例子:函數來處理多個現有獨立的數據定義
data Fruit = Apple String Bool
| Cherry String String
| Grape String
data Vegetable = Carrot String
| Onion Bool String
| Tomato String String
現在我想有應進行兩種類型的函數,我想是這樣的:
f :: a -> String
f (Carrot s) = s
f (Apple s b) = s
f (Onion b s) = s
...
但是這不起作用,因爲預期類型a
不能與例如類型Carrot
匹配。我想知道如何在模式匹配或其他技術的幫助下定義一個可以處理多個現有獨立數據定義的函數。
您可以定義一個'˚F::無論是果蔬 - > String',也可以定義一個類型類(和定義兩個'f's)。 –
@WillemVanOnsem謝謝你的提示。我是對的,'只有'只有兩種類型? –
沒有一種類型,即「任何水果蔬菜」類型。所以你寫'f(Left(Apple s b))= ...','f(Right(Carrot c))= ...'。 –