NOTE: bounded polymorphism
source link: https://dannypsnl.github.io/blog/2020/01/24/cs/note-bound-polymorphism/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
NOTE: bounded polymorphism
Bounded polymorphism refers to existential quantifiers(∃\exists∃), restricted to range over types of bound type. To understand it only needs a few examples. Let's start! Take a look at the following program:
numSort :: Num a => [a] -> [a]
Num a
is how we represent the bounded polymorphism in Haskell, the definition of Num
was class Num b where
(Hoogle shows a
, just prevent to confuse reader don't familiar with Haskell) could read as a type b
is an instance of class Num
.
So numSort
takes [a]
only if a
is an instance of Num
. Now we could run down:
numSort [1, 2, 3] :: [Int]
numSort [1.1, 2, 3] :: [Double]
This is really a powerful feature(and you don't need to use Haskell for this, Java also has this feature), consider the old way to do List<A>
to List<B>
, and unfortunately solution was to copy each element in the list.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK