on 4e50855 help sign in
generic-lens/examples/Examples.hs
58 lines 1.7 kB history raw
1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE DuplicateRecordFields #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE TypeApplications #-}
6{-# LANGUAGE UndecidableInstances #-}
8{-# OPTIONS_GHC -fno-warn-unused-imports #-}
10module Examples where
12import GHC.Generics
13import Data.Generics.Product
14import Control.Lens
16data Animal = Animal
17 { name :: String
18 , age :: Int
19 , eats :: String
20 } deriving (Show, Generic)
22data Human = Human
23 { name :: String
24 , age :: Int
25 , address :: String
26 , eats :: String
27 } deriving (Show, Generic)
29data Living
30 = Animal' { name :: String, eats :: String, age :: Int }
31 | Human' { name :: String, age :: Int, address :: String, eats :: String }
32 deriving (Show, Generic)
34toby :: Human
35toby = Human { name = "Toby", age = 10, address = "London", eats = "Bread" }
37growUp :: Animal -> Animal
38growUp (Animal n a _) = Animal n (a + 10) "raw meat"
40data MyRecord = MyRecord { field1 :: Int, field2 :: String } deriving Generic
42--g :: Subtype s MyRecord => s -> String
43--g s = s ^. super @MyRecord . label @"field2"
45data Test a b = Test { fieldInt :: Int, fieldA :: a, fieldB :: b } deriving (Generic, Show)
47-- changedA :: Test Int String
48-- >>> changedA
49-- Test {fieldInt = 10, fieldA = 10, fieldB = "world"}
50changedA = set (field @"fieldA") (10 :: Int) (Test 10 "hello" "world")
52-- changedB :: Test String Int
53-- >>> changedB
54-- Test {fieldInt = 10, fieldA = "hello", fieldB = 10}
55changedB = set (field @"fieldB") (10 :: Int) (Test 10 "hello" "world")
57--changedInt = set (field @"fieldInt") ("hello") (Test 10 "hello" "world")
58-- type error