on 94d377a help sign in
generic-lens/examples/Examples.hs
104 lines 2.7 kB history raw
1{-# LANGUAGE GADTs #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE Rank2Types #-}
4{-# LANGUAGE AllowAmbiguousTypes #-}
5{-# LANGUAGE DataKinds #-}
6{-# LANGUAGE DeriveGeneric #-}
7{-# LANGUAGE DuplicateRecordFields #-}
8{-# LANGUAGE FlexibleContexts #-}
9{-# LANGUAGE NoMonomorphismRestriction #-}
10{-# LANGUAGE PartialTypeSignatures #-}
11{-# LANGUAGE TypeApplications #-}
12{-# LANGUAGE UndecidableInstances #-}
14{-# OPTIONS_GHC -fno-warn-unused-imports #-}
16module Examples where
18import Data.Function ((&))
19import Data.Generics.Internal.Lens
20import Data.Generics.Product
21import Data.Generics.Sum
22import GHC.Generics
24data Animal = Animal
25 { name :: String
26 , age :: Int
27 , eats :: String
28 } deriving (Show, Generic)
30data Human = Human
31 { name :: String
32 , age :: Int
33 , address :: String
34 , eats :: String
35 } deriving (Show, Generic)
37data Living
38 = Animal' { name :: String, eats :: String, age :: Int }
39 | Human' { name :: String, age :: Int, address :: String, eats :: String }
40 deriving (Show, Generic)
42toby :: Human
43toby = Human { name = "Toby", age = 10, address = "London", eats = "Bread" }
45growUp :: Animal -> Animal
46growUp (Animal n a _) = Animal n (a + 10) "raw meat"
48data MyRecord = MyRecord { field1 :: Int, field2 :: String } deriving Generic
50--g :: Subtype s MyRecord => s -> String
51--g s = s ^. super @MyRecord . label @"field2"
53data Test a b = Test { fieldInt :: Int, fieldA :: a, fieldB :: b } deriving (Generic, Show)
55-- changedA :: Test Int String
56-- >>> changedA
57-- Test {fieldInt = 10, fieldA = 10, fieldB = "world"}
58changedA = Test 10 "hello" "world" & field @"fieldA" .~ (10 :: Int)
60-- changedB :: Test String Int
61-- >>> changedB
62-- Test {fieldInt = 10, fieldA = "hello", fieldB = 10}
63changedB = (Test 10 "hello" "world") & field @"fieldB" .~ (10 :: Int)
65--changedInt = set (field @"fieldInt") ("hello") (Test 10 "hello" "world")
66-- type error
68data Animal2 a
69 = Dog (Dog a)
70 | Cat Name Age
71 | Duck Age
72 deriving (Generic, Show)
74data Dog a
75 = MkDog
76 { name :: Name
77 , age :: Age
78 , fieldA :: a
79 }
80 deriving (Generic, Show)
81type Name = String
82type Age = Int
83dog :: Animal2 Int
84dog = Dog (MkDog "Shep" 3 30)
86-- TODO: the error message for this case is ugly
87-- data Dog a
88-- = MkDog
89-- { name :: Name
90-- , age :: Age
91-- , fieldA :: a
92-- , fieldA' :: a
93-- }
94-- deriving (Generic, Show)
96--dog' :: Animal2 String
97dog' = dog & _Ctor @"Dog" . field @"fieldA" .~ "now it's a String"
99stuff ::
100 ( HasPosition 15 s t a String
101 , HasField "test" s' t' a' b'
102 , HasField "bar" a' b' s t
103 ) => s' -> t'
104stuff r = r & field @"test" . field @"bar" . position @15 .~ "hello"