Skip to content

Instantly share code, notes, and snippets.

@hurryabit
Created October 23, 2020 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hurryabit/0793af3a78560eb7a94517d6d9e8f647 to your computer and use it in GitHub Desktop.
Save hurryabit/0793af3a78560eb7a94517d6d9e8f647 to your computer and use it in GitHub Desktop.
{-# LANGUAGE AllowAmbiguousTypes #-}
-- This module contains all definitions from the blogpost
-- "Lenses, do you get it?"
module Bench where
import DA.Record
-- Van Laarhoven lenses
type Lens r a = forall f. Functor f => (a -> f a) -> (r -> f r)
data Record = Record with field1: Int
_field1: Lens Record Int
_field1 f r = fmap (\x -> r with field1 = x) (f r.field1)
makeLens: (r -> a) -> (r -> a -> r) -> Lens r a
makeLens getter setter f r = setter r <$> f (getter r)
lens: forall x r a. HasField x r a => Lens r a
lens = makeLens (getField @x) (flip (setField @x))
-- Implementing the getter
data Const b a = Const with unConst: b
instance Functor (Const r) where
fmap _ (Const x) = Const x
get: Lens s a -> s -> a
get l r = (l Const r).unConst
data Identity a = Identity with unIdentity: a
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
set: Lens s a -> a -> s -> s
set l x r = (l (\_ -> Identity x) r).unIdentity
-- How to micro-benchmark DAML
records = map Record [1..100_000] -- (A)
benchLens = scenario do
_ <- pure () -- (B)
let step acc r =
acc + get (lens @"field1") r -- (C)
let _ = foldl step 0 records -- (D)
pure ()
numbers = [1..100_000]
benchNoop = scenario do
_ <- pure ()
let step acc r =
acc + r
let _ = foldl step 0 numbers
pure ()
-- First numbers
benchBuiltin = scenario do
_ <- pure ()
let step acc r =
acc + r.field1
let _ = foldl step 0 records
pure ()
-- Temporary stop-gap measures
fastLens: forall field r a. HasField field r a => Lens r a
fastLens f r = fmap (\x -> setField @field x r) (f (getField @field r))
benchFastLens = scenario do
_ <- pure ()
let step acc r =
acc + get (fastLens @"field1") r
let _ = foldl step 0 records
pure ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment