我有多個物件,每個物件都與一個字串相關聯。是否有某種模式允許以型別安全的方式獲取所有字串的串列?
data MyObject = Foo | Bar
getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"
-- Bad because not type safe and String duplication
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = ["Foo", "Bar"]
不同的解決方案仍然不是型別安全但減少了字串重復。
data MyObject = Foo | Bar
getObjectString :: MyObject -> String
getObjectString Foo = listOfAllObjectString !! 0
getObjectString Bar = listOfAllObjectString !! 1
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = ["Foo", "Bar"]
uj5u.com熱心網友回復:
MyObject一旦你得到它的所有值,你就可以得到它Enum和Bounded。然后,您將應用getObjectString到每個值以獲取字串值。
data MyObject = Foo | Bar deriving (Enum, Bounded)
getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = map getObjectString [minBound .. maxBound]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316860.html
上一篇:如何檢查元音?
