Skip to content

Records (with optics?) #9

@chris-martin

Description

@chris-martin

Here's a records demo we wrote a while back:

import Numeric.Natural

data Person =
  Person
    { name :: String  -- ^ The person's given name
    , age :: Natural  -- ^ How many years old
    }
    deriving Show

main =
  do
    let a = Person { name = "Alice", age = 47 }
    let b = Person { name = "Bob", age = 50 }
    let c = b{ age = 51 }

    putStrLn (show a)
    putStrLn (show b)
    putStrLn (show c)

    putStrLn ("name: " ++ name c)
    putStrLn ("age: " ++ show (age c))
$ runhaskell records.hs
Person {name = "Alice", age = 47}
Person {name = "Bob", age = 50}
Person {name = "Bob", age = 51}
name: Bob
age: 51

Lately I'm feeling like the Phrasebook should just immediately introduce optics from the start.

{-# LANGUAGE TemplateHaskell #-}

import Numeric.Natural
import Optics

data Person =
  Person
    { _name :: String  -- ^ The person's given name
    , _age :: Natural  -- ^ How many years old
    }
    deriving Show

makeLenses ''Person

main =
  do
    let a = Person { _name = "Alice", _age = 47 }
    let b = Person { _name = "Bob", _age = 50 }
    let c = set age 51 b

    putStrLn (show a)
    putStrLn (show b)
    putStrLn (show c)

    putStrLn ("name: " ++ view name c)
    putStrLn ("age: " ++ show (view age c))

Maybe that's too radical. On the other hand, maybe introducing it now in an extremely simple context is good setup for a later page on doing "deep updates" with composed lenses. I think in a later page we could end up showing how to get a lot of of optics using only view, set, over, and (%) without being overwhelming.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good for new contributorsPull requests welcome!new exampleThis issue is about writing a new example program.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions