Last active
February 23, 2024 09:41
-
-
Save dadhi/3db1ed45a60bceaa16d051ee9a4ab1b7 to your computer and use it in GitHub Desktop.
Functional optics, e.g. Lens, in C# - to simplify access and modification for deep part of immutable value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Inspired by: https://medium.com/@gcanti/introduction-to-optics-lenses-and-prisms-3230e73bfcfe | |
*/ | |
using System; | |
using static System.Console; | |
public static class Program | |
{ | |
public static void Main() | |
{ | |
var x = new X("Lens"); | |
var xs = x.Lens( | |
a => a.S, (_, s) => new X(s)); | |
var lastChar = "".Lens( | |
a => a[a.Length - 1], | |
(a, b) => a.Substring(0, a.Length - 1) + b); | |
var xsLastChar = xs.Compose(lastChar); | |
WriteLine(xsLastChar.Set(x, 'Z').S); | |
WriteLine(xsLastChar.Update(x, char.ToUpper).S); | |
} | |
class X | |
{ | |
public readonly string S; | |
public X(string s) { S = s; } | |
} | |
} | |
public struct Lens<A, B> | |
{ | |
public Func<A, B> Get; | |
public Func<A, B, A> Set; | |
public Lens(Func<A, B> g, Func<A, B, A> s) | |
{ Get = g; Set = s; } | |
} | |
public static class LensExt | |
{ | |
public static Lens<A, B> Lens<A, B>( | |
this A _, //used only for type inference | |
Func<A, B> g, Func<A, B, A> s) => | |
new Lens<A, B>(g, s); | |
public static A Update<A, B>( | |
this Lens<A, B> lens, | |
A a, Func<B, B> update) => | |
lens.Set(a, update(lens.Get(a))); | |
public static Lens<A, C> Compose<A, B, C>( | |
this Lens<A, B> ab, Lens<B, C> bc) => | |
new Lens<A, C>( | |
a => bc.Get(ab.Get(a)), | |
(a, c) => ab.Set(a, bc.Set(ab.Get(a), c))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Enterprise version: