Is there a way to give function signatures a type with a name?
Example and motive:
Lets look at the strategy pattern from OOP. With functional programming it is much simpler.
def sortMySeq(strategy: Seq[Int] -> Seq[Int], unsorted: Seq[Int]): Seq[Int] = ???
//strategies:
def bubbleSort(unsorted: Seq[Int]): Seq[Int] = ???
def quickSort(unsorted: Seq[Int]): Seq[Int] = ???
//usage
sort(quickSort, mySeq)
Now every function f
with the signature Seq[Int] -> Seq[Int]
could be passed to the sortMySeq
function. Even if it is not a sort function.
I though maybe there is a way to make it typesafe by giving this signature a type with a name. Of course we could do:
trait SortAlgorythm {
def sort(unsorted: Seq[Int]): Seq[Int]
}
and the sortMySeq
function becomes:
def sortMySeq(strategy: SortAlgorythm, unsorted: Seq[Int]): Seq[Int] ???
But that’s the original OOP strategy pattern.
If we could do something like this:
functionType SortAlgorythm: Seq[Int] -> Seq[Int]
Where functionType
is a language keyword and SortAlgorythm
is the name of the signature than me have to tell that which functions are sorting functions:
def bubbleSort: _SortAlgorythm = ???
def quickSort: _SortAlgorythm = ???
This is nothing more an fictional example syntax.
With this SortAlgorythms and other functions with the same signature like a reverse function could be told apart. Transforming this to the trait/interface version in the background is one way that the compiler can translate it. So maybe this is just syntactic sugar.
Maybe I miss something that already exists and could be used in such a way. If not I would be glad to hear what you think about it and if this could be a useful addition to the language.