Re: Any reason why backed enums are limited to int and string only?

From: Date: Wed, 31 Mar 2021 18:52:13 +0000
Subject: Re: Any reason why backed enums are limited to int and string only?
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-113885@lists.php.net to get a copy of this message
Hi Olle > I was trying to implement the result type from OCaml using enums, and > noticed that they can only carry int or string data, not arbitrary > data. Any specific reason for this? > > Example: > > enum Result: mixed { > case Ok = null; > case Error = null; > } > > Error with: > > Fatal error: Enum backing type must be int or string, mixed given in > /tmp/enum.php on line 3 > > More specifically, for this idiom to work, "Ok" needs to be mixed and > "Error" should be string. > > OCaml idiom: > https://ocaml.org/learn/tutorials/error_handling.html#Result-type What you're trying to achieve here is not what backed enums are for. Backed enums are for assigning each enum case a single, constant representation that can be converted back and forth. As for Result, what you'd want here is a dynamic, arbitrary value for both Ok and Error, which is exactly what ADTs / tagged unions would allow you to do: https://wiki.php.net/rfc/tagged_unions enum Result { case Ok(mixed $result); case Error(mixed $error); } Optimally we'd define Result as "Result<TOk, TError>" but that's another discussion :) Note that work on ADT hasn't started yet. Ilija

« previous php.internals (#113885) next »