Questions tagged [lenses]

In functional programming, a lens is a composable field accessor. Lenses allow nested data structures to be manipulated in a concise and side-effect-free way.

lenses
Filter by
Sorted by
Tagged with
3 votes
1 answer
1k views

Modify state using a monadic function with lenses

My question is quite similar to How to modify using a monadic function with lenses? The author asked if something like this exists overM :: (Monad m) => Lens s t a b -> (a -> m b) -> s -&...
maiermic's user avatar
  • 4,914
2 votes
2 answers
182 views

Extending structures in Haskell

I want to implement some algorithms that have a common set of parameters (in practice this is a high number, which is why I am not passing them separately into the functions): data Parameters = ...
Misguided's user avatar
  • 1,302
2 votes
1 answer
82 views

What happens with universal quantifications and typeclass constraints when composing functions?

Lenses can be composed like any ordinary function. We have: Lens' a b = forall f . Functor f => (b -> f b) -> a -> f a Now consider this example: (.) :: Lens' Config Foo -> Lens' Foo ...
Damian Nadales's user avatar
3 votes
1 answer
1k views

Error with 'never' type when using extends keyof as generic type

My code in typescript: class Author { id: number; } type Getter<S, A> = (obj: S) => A; function propGetter<S, K extends keyof S>(prop: K): Getter<S, S[K]> { return o => o[...
dhuCerbin's user avatar
  • 249
0 votes
1 answer
161 views

Haskell: use or uses in Getter

In Control.Lens we have Getter that can access the nested structure. Getter has use and uses, but it's not clear to me how they work. So it'd be great if someone can provide some simple examples that ...
4xx's user avatar
  • 165
4 votes
1 answer
479 views

Recursive Type Lensing

I'm trying to create some code that can take any recursive grammar data type and any expression of that data type and produce a list of all sub-expressions of the same type, built up, kind of like a ...
Julian Leviston's user avatar
2 votes
0 answers
50 views

How to use polymorphic datatypes with fclabels?

TL;DR: I want to use fclabels with my polymorphic datatype, but obtaining wired errors with it. data R a = A { cb :: a } | B { cb :: a, cd :: a} deriving (Show, Read, Eq) So, my type is a ...
Pavel Yakovlev's user avatar
3 votes
1 answer
614 views

Shorter way to traverse nested record with Maybe

Is there a shorter/cleaner way of writing the following snippet of code: fromMaybe "" $ fmap (^. fullName) (bi ^. bookerContact) Here bi ^. bookerContact may result in a Maybe Contact record, which ...
Saurabh Nanda's user avatar
2 votes
1 answer
389 views

How to fix this Purescript error: Could not match {...} with (...)?

I have a state for a halogen component including a lens like this: import Optic.Core (Lens', lens) type State = { userName :: String , password :: String , formError :: String } _userName ::...
ruben.moor's user avatar
  • 1,915
-1 votes
1 answer
417 views

Traversing and adding elements to a Data.Tree using Lenses in Haskell

I'm starting to use lenses and until now I've been unable to use them in a concrete part of a codebase I'm writing. My objective is to update a rose tree structure such as the one in Data.Tree by ...
Jesuspc's user avatar
  • 1,714
0 votes
1 answer
124 views

Using a Lens on a non-case class extending something with a constructor in Scala

I am probably thinking about this the wrong way, but I am having trouble in Scala to use lenses on classes extending something with a constructor. class A(c: Config) extends B(c) { val x: String =...
Charles Menguy's user avatar
2 votes
1 answer
45 views

Renfield: How Do I Get This Traversal To Work?

I have a some nested records (reduced to relevant fields). data GameS = GameS { _game_data_gs :: GameData } data GameData = GameData { _players_gd :: PlayerMap } data PlayerMap = PlayerMap { ...
user avatar
0 votes
0 answers
59 views

How to build up modifications and apply them at once using lenses in Scala?

I have designed a case class that looks superficially like this: case class Moo(foos: Seq[Foo], bar: Bar) { require(foos.length == bar.baz.length) ... } This type will be consumed by a Java ...
Roberto Bonvallet's user avatar
6 votes
2 answers
593 views

Is there a direct way to combine setters for multiple record fields to a single setter?

import Control.Lens import Control.Lens.TH data Foo = Foo { _bar, _baz :: Int } makeLenses ''Foo Now if I want to modify both int fields, I can do barbaz :: Setter' Foo Int barbaz = sets $ \...
leftaroundabout's user avatar
4 votes
1 answer
1k views

Modify Haskell nested record by value

Say I have a nested structure as follows: data Bar = Bar { _id :: Integer, _bars :: [Bar] } data Foo = Foo { _bars :: [Bar] } And I have a Foo with a bunch of Bars with various ids: foo = Foo [Bar ...
clmn's user avatar
  • 43
1 vote
2 answers
100 views

HTTP Lens for interfacing with an API?

I'm just starting to pick up momentum with Haskell, and loving the abstractions I run into daily, such as lens. I'm to a point where a REST API lens would be useful to work with, but before I spend ...
Josh.F's user avatar
  • 3,736
1 vote
1 answer
591 views

Defining optional values in a path built with composed optics

I have a structure of nested case classes that I create with default values: case class Alpha(text: String = "content") case class Beta(alpha: Alpha = Alpha()) case class Gamma(beta: Option[Beta] = ...
qtwo's user avatar
  • 507
1 vote
2 answers
458 views

Lens Laws: what are they trying to tell me?

I've seen various versions of the Lens Laws. Not sure if they're all intended to be equivalent, so for definiteness I'll use the version on StackOverflow against tag Lenses [Edward Kmett ~ 5 years ago]...
AntC's user avatar
  • 2,760
1 vote
2 answers
310 views

Convenient ways to initialize nested fields with lenses

I have some data type which is very similar to ordinary trees, just some specialized form. data NestedTree = NT { _dummy :: Int , _tree :: HashMap String NestedTree } deriving (Show) ...
Shersh's user avatar
  • 9,089
2 votes
3 answers
145 views

Using lenses to compose functions

Consider "composition" functions with the following (pseudo) signature: (a1 -> a2 -> ... -> an -> r) -> (s -> ai) -> a1 -> a2 -> ... -> ai -> ... an -> r where i ...
Clinton's user avatar
  • 22.8k
3 votes
1 answer
313 views

cost of equality when using monocle/scalaz lenses

I was reading about Diode, and it made me think about lenses in Monocle / Scalaz: If I (conditionally) modify deeply some part of a deeply nested data-structure using Monocle/Scalaz lens and want to ...
jhegedus's user avatar
  • 20.5k
1 vote
1 answer
105 views

Adjacent component interaction in Thermite

A difficult test of UI design patterns turns out to be a simple task: Create a generic component (in our case, a button) use it in a parent component get the child component to "actuate" effects in ...
Athan Clark's user avatar
  • 3,896
1 vote
1 answer
192 views

Zoom monad stack maintaining context

Time for my weekly lens question; I have a monad stack: newtype Action a = Action { runAct :: StateT ActionState (ReaderT Hooks IO) a } deriving (Functor, Applicative, Monad, MonadState ...
Chris Penner's user avatar
  • 1,891
6 votes
1 answer
118 views

How to non-impredicatively return `Maybe` a lens?

A type like Maybe (Lens' a b) doesn't work because Lens' is under the hood a Rank-2 type, that can't be wrapped in a type constructor without the -XImpredicativeTypes extension (which is not really ...
leftaroundabout's user avatar
2 votes
1 answer
243 views

How to make lenses for records with type-families [duplicate]

Here's what I've got, which is not compiling: {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ...
Saurabh Nanda's user avatar
0 votes
1 answer
296 views

How to reduce boilerplate with monocle in scala

I've refactored my code for day 12 of advent of code by using monocle, a lens library in scala. Is it possible to improve this code : type Register = String type Mem = Map[String, Int] @...
Yann Moisan's user avatar
  • 8,211
5 votes
0 answers
162 views

Understanding confusing

I've been thinking about whether there's some method that could be added to Traversable to make it compose more cheaply in the presence of expensive functors. The inspiration was Control.Lens....
dfeuer's user avatar
  • 48.3k
3 votes
1 answer
1k views

How to use monocle to modify a nested map and another field in scala

I'm giving a try to monocle for the first time. Here is the case class : case class State(mem: Map[String, Int], pointer: Int) And the current modification, using standard scala, that I would like ...
Yann Moisan's user avatar
  • 8,211
1 vote
1 answer
2k views

How to map properties of an object to constructor arguments in C# for auto copy construction

I have an immutable object. For example the simple case below. class Person { public string Name {get;} public int Age {get;} public Person(string name, int age){ Name = name; ...
bradgonesurfing's user avatar
7 votes
1 answer
428 views

Modifying an attribute with Monocle Lenses using the value of another attribute

I have the following model import monocle.macros.Lenses import monocle.function.all._ import monocle.std.list._ @Lenses("_") case class Poll(pollChoices: List[PollChoice], totalVoteCount: Int) @...
Daniel B.'s user avatar
  • 929
2 votes
1 answer
276 views

How to move from external function to functional lens

On my journey to start getting better with functional programming, I discovered, with the help of a member of the SO family, what lens. I even made some research on it with the links down below to ...
Kevin Avignon's user avatar
2 votes
2 answers
434 views

Combining prisms when extracting JSON fields with lens-aeson

I have a JSON blob similar to the following: [ { "version": 1 }, { "version": "3" }, ... ] Note that some of the versions are numbers and some are strings. I want to get a list of ...
Hapal's user avatar
  • 135
14 votes
3 answers
714 views

Simulating interacting stateful objects in Haskell

I'm currently writing a Haskell program that involves simulating an abstract machine, which has internal state, takes input and gives output. I know how to implement this using the state monad, which ...
N. Virgo's user avatar
  • 8,171
3 votes
1 answer
493 views

How to get classy lenses with overloaded field names?

I'm trying to build lenses for records which have the same field names. Along with that, I'm trying to "wrap/extend" these base records and want the same field names to work for the wrapped/extended ...
Saurabh Nanda's user avatar
7 votes
2 answers
632 views

Is it possible to implement a bidirectional relationship between two structs using only constant properties?

My use case is based on the following model: struct Person { let name: String let houses: [House] } struct House { let owner: Person } Now, ideally I would like to maintain a bidirectional ...
nburk's user avatar
  • 22.6k
1 vote
0 answers
108 views

Serialize object with field of type MkFieldLens

How can I serialize the following class, either by modifying it or by forking Shapeless and modify the source of i.e. MkFieldLens? case class IdHolder[T](t: T)(implicit l:...
eirirlar's user avatar
  • 812
2 votes
1 answer
455 views

How to modify value and type in JSON using argonaut lens?

Assume the following simple JSON document: { "key" : "val1" } I'd like to update the value of "key" but at the same time also change its type, so from string change it to an ...
cpard's user avatar
  • 330
1 vote
0 answers
157 views

Prefix lenses for a type

I have the following data declared: data Something = Something { self :: String , id :: String , description :: Maybe String , name :: String }...
qwe's user avatar
  • 806
22 votes
2 answers
530 views

Isn't it redundant for Control.Lens.Setter to wrap types in functors?

I'm watching the Control.Lens introduction video. It makes me wonder why is it needed for the Setter type to wrap things in functors. It's (roughly) defined like this: type Control.Lens.Setter s t a ...
qwe's user avatar
  • 806
3 votes
1 answer
141 views

Implement choosing over 2 lenses in haskell

I'm practicing for my exam Haskell in 2 weeks. Now I'm making some exercises, but I'm stuck on this one. Implement a function choosing that is given 2 lenses and should return a new lens that ...
user avatar
10 votes
2 answers
2k views

Filtering Lists in Scala's Monocle

Given the following code: case class Person(name :String) case class Group(group :List[Person]) val personLens = GenLens[Person] val groupLens = GenLens[Group] how can i "filter" out ...
Lazarus535's user avatar
  • 1,268
3 votes
1 answer
354 views

What is the syntax for composing setter lenses?

I'm new to lens and I want to compose two "setter" operations to be equivalent to this state0 to new_state2 transformation: let new_state1 = field1 %~ (const newVal1) $ state0 let new_state2 = ...
daj's user avatar
  • 7,082
20 votes
2 answers
15k views

Ramda js: lens for deeply nested objects with nested arrays of objects

Using Ramda.js (and lenses), I want to modify the JavaScript object below to change "NAME:VERSION1" to "NAME:VERSION2" for the object that has ID= "/1/B/i". I want to use a lens because I want to ...
Greg Edwards's user avatar
6 votes
1 answer
239 views

Lenses in Prolog via DCG, possible or not?

Was playing around with lenses in Prolog. Lenses are a kind of microscope that allow to zoom into a structure and do some reads or writes in a functional fashion. Basically my point of departure was ...
user avatar
0 votes
2 answers
95 views

Composable Lensing

I have the following Haskell types import Control.Lens import Data.Map.Lens import qualified Data.Map as M type RepoStats = M.Map String (M.Map String RepoStat) data RepoStat = RepoStat { ...
Steve's user avatar
  • 1,626
2 votes
1 answer
711 views

How to use lens set function with Maybe?

I have a tuple x and a Maybe value y x = (1,1) y = Just 2 I can do this z = maybe x (\v -> x & _1 .~ v) y Or I can create my own operator (.~?) x y = x %~ (\v -> fromMaybe v y) z = x &...
ais's user avatar
  • 2,544
1 vote
1 answer
82 views

How do I turn this into a Setter?

setOwner :: File -> User -> File setOwner f o = f & ownerID .~ (o ^. User.uid) How do I turn this into a Setter? I can't make it a lens because getUser :: UserID -> IO User is an impure ...
Joe Hillenbrand's user avatar
6 votes
1 answer
124 views

What is the name for reverse lens?

Lens is a function that perform immutable record modification: it copies the record modifying part of its content. Lenses is a library that allows you to combine lenses to attain more complicated ...
ayvango's user avatar
  • 5,947
2 votes
2 answers
1k views

Extracting values from JSON Array of JSON Objects using Argonaut Lenses

It's my first time using argonauts and only have a small knowledge of lenses (enough to get by). I've spent a while trying to figure out the problem myself but getting nowhere. I'm trying to build a ...
FintanH's user avatar
  • 110
7 votes
2 answers
2k views

How to compose lenses that return Maybe (Haskell)

Suppose I have a lens like at _ that needs some Maybe a: import Data.Map as M m = M.fromList [(1,(2,3))] --set 2nd element m ^. at 1 .~ Just (4,5) --gives fromList [(1,(4,5))] m ^. at 1 .~ Nothing --...
holdenlee's user avatar
  • 969