lundi 4 octobre 2021

List of all possible values of a function

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




Aucun commentaire:

Enregistrer un commentaire