fantasy-land
fantasy-land copied to clipboard
Catamorphism?
Would it be possible to add a requirement for all ADTs that conform to the Fantasy Land spec that they expose a cata
/fold
/[adt]
method (where [adt]
is a lower case version of the name of the ADT)? This is not as necessary in, say, Haskell, because an ADT comes with a set of type destructors (the type constructors when appearing in a pattern match).
This would allow APIs like that suggested in #151, where a method that takes an ADT and depends on a fold method being present.
Unfortunately, I do not think the general version is typeable and describing it in the language of the spec may be hard as well. Here's an attempt at a plain English definition of the Haskell equivalent:
The
fold
method takes one argument for each data constructor of the data type. Each argument must have the same arity as its corresponding data constructor. Other than the result type, its signature will match that of the data constructor with all type variables replaced with their value in the concrete type. Its result type may be any variablec
that is the same across all arguments tofold
.
I don't know if there's a way to get at this idea without the "hidden model" of type theory that unifies the laws of the methods. Even given that, I can imagine many may be against the idea. I thought it was probably worthwhile writing this issue and getting feedback
It would be possible to type fold
if it's not variadic:
-- e.g.: either.fold(whenLeft, whenRight)
fold :: t a b -> (a -> c) -> (b -> c) -> c
-- e.g.: trilean.fold3(whenTrue, whenFalse, whenUnknown)
fold3 :: t a b c -> (a -> d) -> (b -> d) -> (c -> d) -> d
-- e.g.: future.fold4(whenPending, whenCancelled, whenRejected, whenResolved)
fold4 :: t a b c d -> (a -> e) -> (b -> e) -> (c -> e) -> (d -> e) -> e
But I dunno if all fold
implementations out there are for ADTs with two variants.
But I dunno if all fold implementations out there are for ADTs with two variants.
That would be a nope.
I do not think the general version is typeable and describing it in the language of the spec may be hard as well
Indeed.
But I do think we should have this discussion and it's already given some insights :+1:
That's true! Still tough to communicate which arity is appropriate, as data constructors are not mentioned at any point by the spec.
On the existence of fold3
, elm-these has these
Maybe i should add fold3 to these 😄
That library suggests that cata
might be a good name as lots of stuff is based off daggy. Of course it will have to be 'fantasy-land/cata'. Outside of daggy-implemented stuff, I mostly see [adt]
(e.g. maybe
, either
, these
)
I bet @puffnfresh wouldn't mind donating daggy to fantasy-land tbh.