Function Composition vs Object Composition
In functional programming, we create large functions by composing small functions; in object-oriented programming, we create large objects by composing small objects. They are different types of composition. They might sound similar, but there is something fundamentally different. Let me explain.
In the function world, there is a compose operator, which works for all functions. Say you have 2 functions, one converts an epoch represented by a long integer to a date, the other converts a date to its textual representation.
epochToDate :: Long -> Date
dateToString :: Date -> String
If you want to convert an epoch to the textual representation of its corresponding date, you just compose the 2 functions:
epochToString :: Long -> String
epochToString = compose(epochToDate, dateToString)
The point is that the compose operator (an higher-order function) is always there to serve. It is one works for all. When you write a new function, you automatically get the nice compose operator. With an analogy, think Unix pipe. If you write your program to get input from STDIN and print your output to STDOUT, you automatically get the nice pipe operator | which allows your program to work seamlessly with other programs in that ecosystem.
Is there such a thing in the object world? Not! You have to write your own code to express the composition, there is no one general compose operator which works for all object compositions.
In the function world, there are much more nice operators than the compose operator for you to leverage: functors, monads, monad transformer, a whole bunch of general operators at your disposal. Say we need a function which converts a list of epoch long integers to a list of textual representation of date.
epochListToStringList :: List<Long> -> List<String>
Do you need to implement this function with a for loop? No! Use List functor:
epochListToStringList = compose(List.map(epochToDate), List.map(dateToString))
List
is a functor whose map
function turns any function of type T -> U
into another function of type List<T> -> List<U>
. This is functor, mapping one category to another, the 2 categories are isomorphic. Is there such a nice thing in the object world? Not, again!
As you can see, functions are born in a harmonious ecosystem. Whenever you write a function, you automatically enjoy compose, functors, monads, monad transformers, bla bla...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库