Associate a value with a type in Haskell using a typeclass

  • A+

I want to use a typeclass to return a String instance that is functionally dependent upon a Haskell type. For example, imagine we have the type Form. I want to associate the string "form" with this type. Given the type Invocation, I want to associate the string "job". And so on. The important thing is that I will often not have an instance of the type in question, though the type will be in the type signature of any function that uses it.

Perhaps an easy way to demonstrate this is with Swift:

protocol Resource {   static var resourcePathSegment: String { get } }  struct Form : Resource {     static let resourcePathSegment = "form" }  struct Invocation: Resource {     static let resourcePathSegment = "job" }  print(Form.resourcePathSegment) 

Why would I want such a thing? I'm talking to a REST API that uses certain conventions. For a GET request, the path segment to the resource in question is functionally dependent upon the type of the data returned from the request. However, I won't have an instance of this type until the request completes.


Using TypeApplications, this is easy:

{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}  class Resource a where   resourcePathSegment :: String  instance Resource Form where   resourcePathSegment = "form"  instance Resource Invocation where   resourcePathSegment = "job" 

To illustrate how to use the above:

ghci> :t resourcePathSegment resourcePathSegment :: Resource a => String ghci> resourcePathSegment @Form "form" ghci> resourcePathSegment @Invocation "job" 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: