Created
April 2, 2018 11:11
-
-
Save kosmikus/3db332604190637bc93cede5031ea0e3 to your computer and use it in GitHub Desktop.
Generic validation using generic-sop
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
{-# LANGUAGE DeriveAnyClass #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE TypeFamilies #-} | |
module Person where | |
import Generics.SOP | |
import qualified GHC.Generics as GHC | |
data Person' f = | |
Person | |
{ pName :: HKD f String | |
, pAge :: HKD f Int | |
} deriving (GHC.Generic, Generic) | |
type family HKD (f :: * -> *) (a :: *) :: * where | |
HKD I a = a | |
HKD f a = f a | |
type Person = Person' I | |
type MaybePerson = Person' Maybe | |
validate :: | |
( Generic (a f), Generic (a I), Applicative f | |
, AllZip2 (LiftedCoercible I f) (Code (a f)) (Code (a I)) | |
) => a f -> f (a I) | |
validate = | |
(to <$>) . hsequence . hcoerce . from | |
validatePerson :: Person' Maybe -> Maybe (Person' I) | |
validatePerson = validate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generalising a bit: