zoukankan      html  css  js  c++  java
  • 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...

  • 相关阅读:
    IDE-Android Studio 导入Ecplise项目不改变结构
    IDE-Android Studio -FAQ-使用习惯(不断更新 欢迎留言)
    IDE-Ecplise-代码注释 模版 编码规范 配色
    android- 远程调试
    phpstorm所有快捷键表格pdf
    phpstorm修改字体和大小
    phpstorm重构代码形式让阅读更简单
    七牛云到底好不好使用经历分享
    一篇文章搞懂php中类型转换
    彻底解决php判断a==0为真引发的问题-类型转换
  • 原文地址:https://www.cnblogs.com/weidagang2046/p/function-composition-vs-object-composition.html
Copyright © 2011-2022 走看看