2

I'd like to know if there is any way to create a function that, given a list of names/identifiers e.g. [Monday, Tuesday, ...], automatically creates a datatype day = Monday | Tuesday | ... and a function next such that next Monday = Tuesday, next Tuesday = Wednesday, ... preserving (and reflecting) the order of the identifiers in the list. I know I can do this by hand, but I was wondering if datatype declarations are even possible within functions. If this isn't possible in SML, what are some languages (preferably functional) that allow this?

1
  • 1
    Not possible in SML (what would the type of such a function be? There isn't an SML type whose values are types). Python functions can create classes, but that probably isn't sufficiently functional for you. Maybe Lisp macros might interest you. Along that line, perhaps clojure (which is based on Lisp but is more functional) might have something. What you are trying to do is unlikely to play nicely with type inference. Commented Oct 5, 2018 at 19:22

1 Answer 1

3

This is not possible in Standard ML. (In some implementations, you can actually write a file and read it at run time using use, but that is generally frown upon.)

Haskell can do this:

$ ghci
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Prelude> data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving (Enum, Show)
Prelude> succ Mon
Tue
Prelude> succ Sun
*** Exception: succ{Day}: tried to take `succ' of last tag in enumeration
CallStack (from HasCallStack):
  error, called at <interactive>:5:62 in interactive:Ghci2

The deriving clause tells the compiler to automatically implement the Enum class, which provides the succ function. (The Show class is only there so that we can print the results.) deriving is an ad-hoc mechanism built into the Haskell compiler, but GHC provides many meta-programming facilities.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't seem to be a case of dynamically taking a list and at run time creating a new enumeration type.
I obviously assumed that the list was presented at compile time. Maybe the question is unclear about that part.
The question itself wasn't clear on that point. Your answer is a good answer to one interpretation (+1).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.