我有類似的型別
data Fruit = Apple Date
| Balana Date
| Orange Date
f = [Apple 2020-01-01 ,Apple 2020-02-01
,Balana 2020-01-01 ,Balana 2020-02-01]
getDate:: Fruit -> Date
getDate (Apple x) = x
getDate (Balana x) = x
getDate (Orange x) = x
f按date欄位排序串列時。
instance Ord Fruit where
compare f1 f2 = compare (getDate f1) (getDate f2)
但是,問題是,如何設定規則來訂購 Apple 2020-01-01和Balance 2020-01-01?
如果我想先排序日期,如果date不同型別的水果相同,我會Apple先排序,然后Balance呢Orange?
[Apple 2020-01-01, Balance 2020-01-01, Apple 2020-02-01 ,Balana 2020-02-01]
謝謝 !
uj5u.com熱心網友回復:
您可以使用一些不同的方法:
最直截了當的不是你想知道的,而是有用的
data Fruit = Apple Date
| Balana Date
| Orange Date
deriving (Eq, Ord)
這會為您輸入自動訂單,但在這種情況下,它會先比較水果,然后再比較Date......這與您想要的相反。
因此我們需要手動定義一個Ord實體。
-- This get the date from fruit
getDate :: Fruit -> Date
getDate (Apple x) = x
getDate (Balana x) = x
getDate (Orange x) = x
-- This function compares the fruit with no date.
fruitOrder :: Fruit -> Fruit -> Ordering
fruitOrder (Apple _) (Apple _) = EQ
fruitOrder (Apple _) _ = LT
fruitOrder (Orange _) (Orange _) = EQ
fruitOrder (Orange _) _ = GT
fruitOrder (Balana _) (Balana _) = EQ
fruitOrder (Balana _) (Apple _) = GT
fruitOrder (Balana _) (Orange _) = LT
-- Your ordering is a combination of both
instance Ord Fruit where
compare f g = comparing getDate f g <> fruitOrder f g
-- | |- This returns the first not EQ value or EQ if both are equal
-- |- comparing func x y == compare (func y) (func y)
不一樣的造型
現在,您可能正在以一種非慣用的方式對您的型別進行建模。如果您的所有專案都有一個日期,那么您應該將您的型別編碼為對,如下所示
-- This is an alternative representation. You have Fruit types ordered as written
data FruitType = Apple | Banana | Orange deriving (Eq, Ord)
-- A fruit is a Date and a FruitType, this is Record syntax
-- you can think of it as C's structs or Python's dataclasses.
data Fruit = Fruit {getDate :: Date, getType :: FruitType} deriving (Eq, Ord)
-- The derived order is lexicographic, meaning they are ordered by the first field, and then by the second field
例如,此程式使用建議的型別按預期排序您的串列
import Data.List
type Date = String -- For the sake of example
-- This is an alternative representation. You have Fruit types ordered as written
data FruitType = Apple | Banana | Orange deriving (Show, Eq, Ord)
-- A fruit is a Date and a FruitType, this is Record syntax
-- you can think of it as C's structs of Python's dataclasses.
data Fruit = Fruit {getDate :: Date, getType :: FruitType} deriving (Show, Eq, Ord)
f = [ Fruit "2020-01-01" Apple
, Fruit "2020-02-01" Apple
, Fruit "2020-01-01" Banana
, Fruit "2020-02-01" Banana]
main = print $ sort f
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528504.html
標籤:哈斯克尔
下一篇:串列中的Haskell資料型別
