sto cercando di definire classi in Java che sono simili a funtori di Haskell. Con la presente, un funtore è definito come:Funtori in Java
/**
* Programming languages allow only (just simply enough) endofunctor, that are functors from and to the same category.
* In this case, the category is the one of the datatypes (in here Type, in order to make it more clear)
*/
public interface EndoFunctor<X extends Type> extends Type {
/**
* The basic implementation for any element fx
* @param map Transformation function for the type parameter
* @param fx Element of the current class
* @param <Y> Target type
* @return transformed element through map
*/
<Y extends Type> EndoFunctor<Y> fmap(Function<X,Y> map, EndoFunctor<X> fx);
}
Se voglio realizzare un funtore , devo scrivere qualcosa di simile
public class Id<X extends Type> implements EndoFunctor<X> {
protected X witness;
Id(X witness) { this.witness = witness; }
@Override
public <Y extends Type> Id<Y> fmap(Function<X, Y> map, Id<X> fx) {
return new Id<>(map.apply(fx.witness));
}
}
Il problema con questo codice è che Id<X>
non corrisponde al tipo di EndoFunctor<X>
. Come potrei stabilire fmap
nel EndoFunctor
dell'interfaccia tale che se qualsiasi tipo K<T>
implementa EndoFunctor<T>
e viene data una funzione di mappa T->U
, quindi K<U>
viene restituito come un valore, senza alcuna fusione di caratteri (cioè da quando so che il mio oggetto è un Id<T>
, allora il risultato di fmap
"deve essere" Id<U>
, e quindi ho abbattuto il risultato di tipo EndoFunctor<U>
a tale tipo)?
C'è un motivo per cui non è stato utilizzato 'EndoFunctor FMAP (Funzione mappa)', invece? In questo modo, ogni istanza utilizzerà le sue variabili di istanza. I.e, 'return new Id <> (map.apply (this.witness))'. –
afsantos
Bene, non penso che questa osservazione possa rispondere alla mia domanda. La tua mappa ('fmap2 (x)') è definibile come 'fmap (x, this)', quindi questo non risolve il problema del tipo. – jackb
A proposito, ho definito la funzione in questo modo per farla somigliare più alla definizione di un funtore, cioè [F: (a-> b) -> (Fa -> Fb)] (http: // latex.codecogs.com/gif.download?F%5Ccolon%20%28a%5Cto%20b%29%5Cto%20%28Fa%5Cto%20Fb%29), dove F in questo caso è EndoFunctor. – jackb