Created
February 19, 2015 21:47
-
-
Save sinelaw/a4a035a5bb6b0d6d6c1c to your computer and use it in GitHub Desktop.
Demo code for https://noamlewis.wordpress.com/2015/02/19/ad-hoc-polymorphism-type-families-ambiguous-types-and-javascript/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# OPTIONS -Wall #-} | |
{-# LANGUAGE TypeFamilies, FlexibleInstances #-} | |
import Data.Map | |
class Indexable a where | |
type Index a | |
type Result a | |
index :: a -> Index a -> Result a | |
instance Indexable [a] where | |
type Index [a] = Int | |
type Result [a] = a | |
index = (!!) | |
newtype Str = Str { getStr :: String } | |
instance Indexable Str where | |
type Index Str = Int | |
type Result Str = Char | |
index = (!!) . getStr | |
instance Indexable (Map String a) where | |
type Index (Map String a) = String | |
type Result (Map String a) = a | |
index = (!) | |
f :: (Indexable a, Index a ~ Int) => a -> Result a | |
f x = index x (0::Int) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment