Some Name
Some Name

Reputation: 9540

Context aware typeclasses

I'm working on some application which works with files on a hard disk. I have the following "entity":

final case class File(path: String)
final case class FileChecksum(f: File, checksum: Long)

I also have the following typeclass:

trait Checksum[T]{
    def checksum(t: T): Long
}

All these is operated by the following trait:

trait Model{
    def fromFile(file: File)(implicit checksum: Checksum[File]): FileChecksum
}

And and it looks fine. But I decided to refactor it and apply tagless final. So the model now looks like:

trait Model[F[_]]{
    def fromFile(file: File)(implicit checksum: Checksum[F, File]): F[FileChecksum]
}

trait Checksum[F[_], T]{
    def checksum(t: T): F[Long]
}

The problem that confused me is the the typeclass trait Checksum[F[_], T]. It now depends on the context F. Is that really a typeclass? Or I'm looking in the wrong direction?

Upvotes: 0

Views: 77

Answers (1)

Ben Weaver
Ben Weaver

Reputation: 970

I believe Checksum[F[_], T] is still a typeclass, but one now parameterized by a higher-kinded type (HKT), that takes a one-argument type constructor.

Thus, F takes as a parameter type constructors such as List or Option. That is:

def checksum(t: T): F[Long]

with its return type F[Long], could be implemented to return List[Long] or Option[Long].

I hope this helps. See also: https://typelevel.org/blog/2016/08/21/hkts-moving-forward.html and https://www.atlassian.com/blog/archives/scala-types-of-a-higher-kind

Upvotes: 2

Related Questions