When are higher kinded types useful?

后端 未结 5 1394
一向
一向 2021-01-29 18:21

I\'ve been doing dev in F# for a while and I like it. However one buzzword I know doesn\'t exist in F# is higher-kinded types. I\'ve read material on higher-kinded types, and

5条回答
  •  旧巷少年郎
    2021-01-29 19:06

    The most-used example of higher-kinded type polymorphism in Haskell is the Monad interface. Functor and Applicative are higher-kinded in the same way, so I'll show Functor in order to show something concise.

    class Functor f where
        fmap :: (a -> b) -> f a -> f b
    

    Now, examine that definition, looking at how the type variable f is used. You'll see that f can't mean a type that has value. You can identify values in that type signature because they're arguments to and results of a functions. So the type variables a and b are types that can have values. So are the type expressions f a and f b. But not f itself. f is an example of a higher-kinded type variable. Given that * is the kind of types that can have values, f must have the kind * -> *. That is, it takes a type that can have values, because we know from previous examination that a and b must have values. And we also know that f a and f b must have values, so it returns a type that must have values.

    This makes the f used in the definition of Functor a higher-kinded type variable.

    The Applicative and Monad interfaces add more, but they're compatible. This means that they work on type variables with kind * -> * as well.

    Working on higher-kinded types introduces an additional level of abstraction - you aren't restricted to just creating abstractions over basic types. You can also create abstractions over types that modify other types.

提交回复
热议问题