on 4eb9475 help sign in
generic-lens/examples/Examples.hs
86 lines 2.3 kB history raw
1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE DuplicateRecordFields #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE NoMonomorphismRestriction #-}
6{-# LANGUAGE PartialTypeSignatures #-}
7{-# LANGUAGE TypeApplications #-}
8{-# LANGUAGE UndecidableInstances #-}
10{-# OPTIONS_GHC -fno-warn-unused-imports #-}
12module Examples where
14import Data.Function ((&))
15import Data.Generics.Internal.Lens
16import Data.Generics.Product
17import Data.Generics.Sum
18import GHC.Generics
20data Animal = Animal
21 { name :: String
22 , age :: Int
23 , eats :: String
24 } deriving (Show, Generic)
26data Human = Human
27 { name :: String
28 , age :: Int
29 , address :: String
30 , eats :: String
31 } deriving (Show, Generic)
33data Living
34 = Animal' { name :: String, eats :: String, age :: Int }
35 | Human' { name :: String, age :: Int, address :: String, eats :: String }
36 deriving (Show, Generic)
38toby :: Human
39toby = Human { name = "Toby", age = 10, address = "London", eats = "Bread" }
41growUp :: Animal -> Animal
42growUp (Animal n a _) = Animal n (a + 10) "raw meat"
44data MyRecord = MyRecord { field1 :: Int, field2 :: String } deriving Generic
46--g :: Subtype s MyRecord => s -> String
47--g s = s ^. super @MyRecord . label @"field2"
49data Test a b = Test { fieldInt :: Int, fieldA :: a, fieldB :: b } deriving (Generic, Show)
51-- changedA :: Test Int String
52-- >>> changedA
53-- Test {fieldInt = 10, fieldA = 10, fieldB = "world"}
54changedA = Test 10 "hello" "world" & field @"fieldA" .~ (10 :: Int)
56-- changedB :: Test String Int
57-- >>> changedB
58-- Test {fieldInt = 10, fieldA = "hello", fieldB = 10}
59changedB = (Test 10 "hello" "world") & field @"fieldB" .~ (10 :: Int)
61--changedInt = set (field @"fieldInt") ("hello") (Test 10 "hello" "world")
62-- type error
64data Animal2 a
65 = Dog (Dog a)
66 | Cat Name Age
67 | Duck Age
68 deriving (Generic, Show)
70data Dog a
71 = MkDog
72 { name :: Name
73 , age :: Age
74 , fieldA :: a
75 }
76 deriving (Generic, Show)
77type Name = String
78type Age = Int
79dog, cat, duck :: Animal2 Int
80dog = Dog (MkDog "Shep" 3 30)
81cat = Cat "Mog" 5
82duck = Duck 2
85--dog' :: Animal2 String
86dog' = dog & _Ctor @"Dog" . field @"fieldA" .~ "now it's a String"