HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulelinear-base-0.4.0Haskell2010

Control.Optics.Linear.Traversal

This module provides linear traversals.

Traversals provides a means of accessing several as organized in some structural way in an s, and a means of changing them to bs to create a t. In very ordinary language, it's like walking or traversing the data structure, going across cases and inside definitions. In more imaginative language, it's like selecting some specific as by looking at each constructor of a data definition and recursing on each non-basic type (where basic types are things like Int, Bool or Char).

Example

{-# LANGUAGE LinearTypes #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}

import Control.Optics.Linear.Internal
import qualified Control.Functor.Linear as Control
import Control.Functor.Linear (($), (*), pure)
import Prelude.Linear

-- We can use a traversal to append a string only to the
-- human names in a classroom struct
appendToNames :: String -> Classroom %1-> Classroom
appendToNames s = over classroomNamesTrav (name -> name ++ s)

data Classroom where
  Classroom ::
    { className :: String
    , teacherName :: String
    , classNum :: Int
    , students :: [Student]
    , textbooks :: [String]
    } %1-> Classroom

-- A Student is a name and a student id number
data Student = Student String Int

classroomNamesTrav :: Traversal' Classroom String
classroomNamesTrav = traversal traverseClassStr where
  traverseClassStr :: forall f. Control.Applicative f =>
    (String %1-> f String) -> Classroom %1-> f Classroom
  traverseClassStr onName (Classroom cname teachname x students texts) =
    Classroom $
    pure cname *
    onName teachname *
    pure x *
    traverse' ((Student s i) -> Student $ onName s * pure i) students *
    pure texts
  • 2 types
  • 7 values

Types

2 declarations

Composing optics

1 declaration

Common optics

1 declaration

Using optics

4 declarations
valueoverU :: Optic_ (->) s t a b -> (a -> b) -> s -> t
#

Constructing optics

1 declaration