Alias for a function signature

Viewed 107

I am implementing the kNN algorithm in Haskell. I therefore need distance functions. The first one works well

import Data.Composition
import Data.Vector

taxicab :: Num a => Vector a -> Vector a -> a
taxicab = Data.Vector.sum .: Data.Vector.zipWith (\ x y -> abs $ x - y)

How can I create an alias Distance for Num a => Vector a -> Vector a -> a?

I could so write:

taxicab :: Distance
2 Answers

You probably want to define a type synonymn (or see this other page). It is not directly possible to include the class constraint without a parameter¹, but you can have a parametrized type synonym:

type Distance a = Vector a -> Vector a -> a

taxicab :: Num a => Distance a

This allows you to have define Distances with different constraints.


¹ I was initially mistaken: you can if you add a parameter.

Just like you create a type alias for another type:

type Distance a = Num a => Vector a -> Vector a -> a

In fact functions are "type constructors": if you write a -> b, you have, in a more canonical form, written (->) a b, so that means that you have basically written:

type Distance a = Num a => (->) (Vector a) ((->) (Vector a) a)

Note however that we need to add a type parameter a here, so your taxicab is of type:

taxicab :: Distance a
Related