From eefadef0e9d0e34cec75680fddcb4237a2d7c695 Mon Sep 17 00:00:00 2001 From: Gregor Kleen Date: Fri, 11 Dec 2015 14:48:54 +0100 Subject: "generalized" either --- genEither.hs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 genEither.hs diff --git a/genEither.hs b/genEither.hs new file mode 100644 index 0000000..4f6f7ae --- /dev/null +++ b/genEither.hs @@ -0,0 +1,32 @@ +#! /usr/bin/env nix-shell +#! nix-shell -i ghci shell.nix + +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} + +type (:||:) = Either +infixr 1 :||: + +class Contains h n where + extract :: h -> Maybe n + insert :: n -> h + +instance Contains (a :||: b) a where + extract (Left a) = Just a + extract _ = Nothing + insert = Left + +instance Contains (a :||: b) b where + extract (Right a) = Just a + extract _ = Nothing + insert = Right + +instance {-# OVERLAPS #-} Contains h n => Contains (a :||: h) n where + extract (Right a) = extract a + extract _ = Nothing + insert = Right . insert + +test :: Maybe String +test = extract (insert "test" :: String :||: Integer :||: Float) -- cgit v1.2.3