scala - Understanding Type Parameters -
looking @ part of io monad
's signatures functional programming in scala:
trait io[+a] { self => def run: def map[b](f: => b): io[b] = new io[b] { def run = f(self.run) }
as understand, io[+a]
means io
type takes type parameter of "a or subclasses."
looking @ def map[b]...
, b
type involved in function. it's useful use map[b](f: => b): io[b]
since, understand, can list b
return type of f
, returned type parameter of io
?
so, following implementation cause compile-time problem:
map(f: int => string): io[int]
so +a
means similar thing t <: a
. means "for subtypes of including a". "limitation" useful here because supposed pass f
function map
method , restricting specific type a
, it's subtypes. when extend trait in class allow substitution of f
while being typesafe.
b
here result of applying f
a
. since it's monad not b
io[b]
. in other words might fail , might b
wrapped in "success" or sort of "failure".
notice type of self
+a
, , newly created io[b]
not compute anything, wraps around result of run
has b
. since expect failures occur in io , since it's monad wrap around result of application of f(self.run)
creating monad io[b]
(as promised map
method signature).
finally, said map(f: int => string): io[int]
should not compile since int
not subtype of string
.
Comments
Post a Comment