본문 바로가기
Functional Programming

Swift에서의 렌즈(Lens) - Basic

by zinozino 2025. 3. 13.

 

복잡한 데이터구조에서 특정구조에 접근하는 방법을 Lens라는 함수객체로 알아보도록 하겠습니다.

먼저 전체에서 부분을 가져오는 함수를 만들어 보겠습니다.

Whole -> Part (getter)

 

 

전체에서 부분만 수정하는 것도 필요할 거예요 (setter)

Part, Whole => Whole

여기서 Part => Whole가 아닌 이유는

Whole에서 Part를 제외한 다른 부분은 기존의 Whole에 있던 것 그대로 있어야 하기 때문입니다.

 

 

 

그럼 이제 이러한 특성을 가진 함수객체 Lens를 만들어보겠습니다.

//함수객체를 생성할때 get함수와 set함수를 지정해 줄 수 있습니다.
struct Lens<Whole, Part> {
    let view: (Whole) -> Part
    let set: (Part, Whole) -> Whole
}

 

 

 

스트리머라는 데이터타입을 만들었습니다. 스트리머로서 이름과 활동하고 있는 플랫폼을 가지고 있습니다.

struct Streamer {
    let name: String
    let mainPlatform: String
}

 

 

여기서 한 스트리머 정보로 객체화하여 변수에 저장하였습니다.

let streamer = Streamer(name: "궤도", mainPlatform: "Youtube")

 

 

Lens를 통해서 Streamer의 이름을 들여다보겠습니다.

let nameLens = Lens<Streamer, String>(
    view: {streamer in streamer.name },
    set: { newName, streamer in
    	Streamer(name: newName, mainPlatform: streamer.mainPlatform)
    }
)

 

 

스트리머의 이름을 가져오겠습니다.

nameLens.view(streamer)

 

 

스트리머의 이름을 바꿔보겠습니다.

nameLens.set("안될과학", streamer)

 

 

스트리머의 플랫폼을 알아보고, 이적시키도록 들여다보는 Lens를 만들어 보겠습니다.

let mainPlatformLens = Lens<Streamer, String>(
    view: {streamer in streamer.mainPlatform },
    set: {newPlatform, streamer in
    	Streamer(name: streamer.name, mainPlatform: newPlatform)
    }
)

 

 

스트리머의 소속 플랫폼을 가져오겠습니다.

mainPlatformLens.view(streamer)

 

스트리머의 소속 플랫폼을 바꿔보겠습니다.

mainPlatformLens.set("Twitch", streamer)

 

 

음..아직까진 할만하죠잉..🧐

 

 

 


참조:

https://medium.com/javascript-scene/lenses-b85976cb0534

 

Lenses

Composable Getters and Setters for Functional Programming

medium.com

 

 

https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/

 

Category Theory for Programmers: The Preface

Table of Contents Part One Category: The Essence of Composition Types and Functions Categories Great and Small Kleisli Categories Products and Coproducts Simple Algebraic Data Types Functors Functo…

bartoszmilewski.com

 

'Functional Programming' 카테고리의 다른 글

Swift에서의 렌즈(Lens) - Link  (0) 2025.03.15