Skip to content

Instantly share code, notes, and snippets.

@SergeyStretovich
Last active July 26, 2020 08:34
Show Gist options
  • Save SergeyStretovich/9733dfc70b2e1b040a94858bf07fe969 to your computer and use it in GitHub Desktop.
Save SergeyStretovich/9733dfc70b2e1b040a94858bf07fe969 to your computer and use it in GitHub Desktop.
Toying with haskell MultiParamTypeClasses
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
data TestItem b n = TestItem {itemName::b, itemValue::n}
class (Num n,IsString b) => PieChartItem a b n where
getValue :: a -> n
getName :: a -> b
instance (Num n,IsString b) => PieChartItem (TestItem b n) b n where
--getValue (TestItem b n) = n
--getName (TestItem b n) = b
getValue ti = itemValue ti
getName ti = itemName ti
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.String
import qualified Data.Text as T
import qualified Data.Text.IO as I
import Data.Monoid
data TestItem b n = TestItem {itemName::b, itemValue::n}
class (Num n)=> PieChartClass a n where
getValue ::(Num n, PieChartClass a n) => a -> n
class (IsString n)=> HasName a n where
getName ::(IsString n, HasName a n) => a -> n
instance (Num n) => PieChartClass (TestItem b n) n where
getValue ti = itemValue ti
instance (IsString b) => HasName (TestItem b n) b where
getName ti = itemName ti
testIO::IO()
testIO = do
let itemFloat::(TestItem String Float) = TestItem "Jack" 56.6
let itemInt::(TestItem String Int) = TestItem "Bob" 32
let itemFloatT::(TestItem T.Text Float) = TestItem "Jack" 56.6
let itemIntT::(TestItem T.Text Int) = TestItem "Bob" 32
let valueFloat::Float = getValue itemFloat
let valueInt::Int = getValue itemInt
let name::String = getName itemFloat
let nameT::T.Text = getName itemFloatT
putStrLn $ "float value " ++ (show valueFloat)
putStrLn $ "int value " ++ (show valueInt)
putStrLn ("string value " ++ name)
I.putStrLn (("text value "::T.Text) <> nameT)
putStrLn "_"
data TestItem n = TestItem {itemName::String, itemValue::n} deriving Show
class (Num n)=> PieChartClass a n where
getValue ::(Num n, PieChartClass a n) => a -> n
class HasName a where
getName :: a -> String
instance Num n => PieChartClass (TestItem n) n where
getValue ti = itemValue ti
instance HasName (TestItem n) where
getName ti = itemName ti
getPP::(Num n, PieChartClass a n) => a -> n
getPP pci = getValue pci
let itemFloat::(TestItem Float) = TestItem "Jack" 56.6
let itemInt::(TestItem Int) = TestItem "Bob" 34
let valueFloat::Float = getValue itemFloat
let valueInt::Int = getValue itemInt
let name = getName itemFloat
putStrLn $ show valueFloat
putStrLn $ show valueInt
putStrLn name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment