Home > database >  List of all possible values of a function
List of all possible values of a function

Time:10-04

I have multiple objects each associated with a String. Is there some pattern that allows a type safe way to get the list of all Strings?

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"] 

Different solution that is still not type safe but reduces String duplication.

data MyObject = Foo | Bar 

getObjectString :: MyObject -> String
getObjectString Foo = listOfAllObjectString !! 0
getObjectString Bar = listOfAllObjectString !! 1

listOfAllObjectStrings :: [String]
listOfAllObjectStrings = ["Foo", "Bar"]

CodePudding user response:

You can get all values of MyObject once you've made it derive Enum and Bounded. Then, you'll apply getObjectString to each value to get a string value.

data MyObject = Foo | Bar deriving (Enum, Bounded)

getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"

listOfAllObjectStrings :: [String]
listOfAllObjectStrings = map getObjectString [minBound .. maxBound]
  • Related