函数所有可能值的列表
List of all possible values of a function
我有多个对象,每个对象都与一个字符串相关联。是否有某种模式允许以类型安全的方式获取所有字符串的列表?
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"]
一旦你使MyObject
派生Enum
和Bounded
,你就可以获得MyObject
的所有值。然后,您将对每个值应用 getObjectString
以获得字符串值。
data MyObject = Foo | Bar deriving (Enum, Bounded)
getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = map getObjectString [minBound .. maxBound]
我有多个对象,每个对象都与一个字符串相关联。是否有某种模式允许以类型安全的方式获取所有字符串的列表?
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"]
一旦你使MyObject
派生Enum
和Bounded
,你就可以获得MyObject
的所有值。然后,您将对每个值应用 getObjectString
以获得字符串值。
data MyObject = Foo | Bar deriving (Enum, Bounded)
getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = map getObjectString [minBound .. maxBound]