Functional Programming -- Monad

原文: Functional Computational Thinking — What is a monad?

原文作者是在学习了 Haskell 之后,又看到了 Why Do Manods Matter 的相关视频,根据视频中Haskell 函数组合的例子,转用javascript实现(nodejs环境)。

首先 ,我们都知道 函数组合:

const add1 = x => x + 1;
const mul3 = x => x * 3;

const composeF = (f, g) => x => f(g(x));

const add1ThenMul3 = composeF(mul3, add1);
add1ThenMul3(10); // 33

上方的组合函数非常的简单,它接受两个参数f和g,并返回一个新函数,在调用f和g函数后返回结果。我们使用composeF 结合 add1和mul3来形成新的函数 add1ThenMul3.


现在我们假设:
1. 我们有两个文件 file1和file2, file2中包含我们想要的内容,而file2的路径在file1中, 已知file1的路径。
2. 写一个读文件的function.

// 1. 根据file1的路径获得file1文件中的内容, 并返回
// 2. 根据file2的路径获得file2文件中的内容,并返回
// 3. file2的路径是读取file1返回的
const composeF = (f, g) => x => f(g());
const readFileSync = path => fs.readFileSync(path.trim()).toString();

const readFileContentSync = composeF(readFileSync, readFileSync);
readFileContentSync('./file1'); // file2的内容

readfilesync是一个同步io函数,它将路径字符串作为输入并返回字符串中给定路径的内容。
所以可以用componseF来编写想到的函数;


但是如果readfile 是一个异步的过程,那么可以用我们node.js中的回调来进行流控制,这种方式有个正式的名字:continuation-passing-style 或者CPS。

readFile 函数将变为如下:

    const readFileCPS = (path, cb) => {
        fs.readFile(path.trim(), (err, data) => {
            const result = data.toString();
            cb(result);
        });
    }

此时,随着readFile函数的变化,composeF已经不能够正确返回结果了,所以我们需要重写合成函数:

    const composeCPS = (g, f) => {
        return (x, cb) => {
            g(x, y => {
                f(y, z => {
                    cb(z);
                })
            })
        }
    }

    // 使用新的合成函数
    const readFileContentCPS = composeCPS(readFileCPS, readFileCPS);
    readFileContentCPS('./file1', result => console.log(result));

注意:重写的composeCPS的参数顺序被调换了,函数会先调用g 然后调用f,最终cb返回值。


接下来,再做一些有趣的事情
首先,调整readFileCPS的函数声明为readFileHOF, HOF的含义是 高阶函数 [high order function]

    const readFileHOF = path => cb => {
        readFileCPS(path, cb);
    }

重新定义compose函数 composeHOF:

    const composeHOF = (g, f) => {
        return x => cb => {
            g(x)(y => {
                f(y)(cb);
            })
        }
    }

    const readFileContentHOF = composeHOF(readFileHOF, readFileHOF);
    readFileContentHOF('/file1')(result => console.log(result));

继续改进readFileHOF函数:

    const readFileEXEC = path => {
        return {
            exec: cb => readFileCPS(path, cb)
        }
    }

继续改进compose函数 composeEXEC:

    const composeEXEC = (g, f) => {
        return x => {
            return {
                exec: cb => {
                    g(x).exec(y => {
                        f(y).exec(cb)
                    })
                }
            }
        }
    }

    const readFileContentEXEC = composeEXEC(readFileEXEC, readFileEXEC);
    readFileContentEXEC('/file1').exec(result => console.log(result));
Learning C++ Functional Programming by Wisnu Anggoro English | 10 Aug. 2017 | ISBN: 1787281973 | ASIN: B06WVD7CVT | 304 Pages | AZW3 | 2.4 MB Key Features Modularize your applications and make them highly reusable and testable Get familiar with complex concepts such as metaprogramming, concurrency, and immutability A highly practical guide to building functional code in C++ filled with lots of examples and real-world use cases Book Description Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of C++, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the C++ 17 features that can be applied to build software in a functional way. The book is divided into three modules—the first introduces the fundamentals of functional programming and how it is supported by modern C++. The second module explains how to efficiently implement C++ features such as pure functions and immutable states to build robust applications. The last module describes how to achieve concurrency and apply design patterns to enhance your application's performance. Here, you will also learn to optimize code using metaprogramming in a functional way. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis. What you will learn Get to know the difference between imperative and functional approaches See the use of first-class functions and pure functions in a functional style Discover various techniques to apply immutable state to avoid side effects Design a recursive algorithm effectively Create faster programs using lazy evaluation Structure code using design patterns to make the design process easier Use concurrency techniques to develop responsive software Learn how to use the C++ Standard Template Library and metaprogramming in a functional way to improve code optimization About the Author Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has also authored the books Boost.Asio C++ Network Programming - Second Edition and Functional C# by Packt. He has been programming since he was in junior high school, which was about 20 years ago, and started developing computer applications using the BASIC programming language in the MS-DOS environment. He has solid experience in smart card programming, as well as desktop and web application programming, including designing, developing, and supporting the use of applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++. He is currently a senior smart card software engineer at CIPTA, an Indonesian company that specializes in innovation and technology for smart cards. He can be reached through his email at wisnu@anggoro.net. Table of Contents Diving into Modern C++ Manipulating functions in functional programming Applying immutable state to the function Recurring method invocation using recursive algorithm Procrastinating the execution process using Lazy Evaluation Optimizing code with Metaprogramming Running parallel execution using Concurrency Creating and debugging application in functional approach
Explore functional programming and discover new ways of thinking about code. You know you need to master functional programming, but learning one functional language is only the start. In this book, through articles drawn from PragPub magazine and articles written specifically for this book, you'll explore functional thinking and functional style and idioms across languages. Led by expert guides, you'll discover the distinct strengths and approaches of Clojure, Elixir, Haskell, Scala, and Swift and learn which best suits your needs. Contributing authors: Rich Hickey, Stuart Halloway, Aaron Bedra, Michael Bevilacqua-Linn, Venkat Subramaniam, Paul Callaghan, Jose Valim, Dave Thomas, Natasha Murashev, Tony Hillerson, Josh Chisholm, and Bruce Tate. Functional programming is on the rise because it lets you write simpler, cleaner code, and its emphasis on immutability makes it ideal for maximizing the benefits of multiple cores and distributed solutions. So far nobody's invented the perfect functional language - each has its unique strengths. In Functional Programming: A PragPub Anthology, you'll investigate the philosophies, tools, and idioms of five different functional programming languages. See how Swift, the development language for iOS, encourages you to build highly scalable apps using functional techniques like map and reduce. Discover how Scala allows you to transition gently but deeply into functional programming without losing the benefits of the JVM, while with Lisp-based Clojure, you can plunge fully into the functional style. Learn about advanced functional concepts in Haskell, a pure functional language making powerful use of the type system with type inference and type classes. And see how functional programming is becoming more elegant and friendly with Elixir, a new functional language built on the powerful Erlang base.The industry has been embracing functional programming more and more, driven by the need for concurrency and parallelism. This collection of articles will lead you to mastering the functional approach to problem solving. So put on your explorer's hat and prepare to be surprised. The goal of exploration is always discovery. What You Need: Familiarity with one or more programming languages.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值