[Functional Programming] Write simple Semigroups type
An introduction to concatting items via the formal Semi-group interface. Semi-groups are simply a type with a concat method that are associative. We define three semigroup instances and see them in action.
1. What is Semigroups:
Array type, String type, they are semigroup, because both has ´concat´ method:
"a".concat("b").concat("c"); // abc
[].concat([]).concat([]); //[1,2,3]
Sum:
But Number type is not semigroup, because you cannot concat two number... well, for now...
Not let's define a Semigroup for Number as well, it is called 'Sum':
// Sum :: Sum s => a -> s a
const Sum = x => ({
x,
concat: ({x: y}) => Sum(x + y),
inspect: () => `Sum ${x}`
})
Sum takes a variable 'a' and return Sum(a). Here 'a' should be number type. We export 'x' to outside world from Sum is for easy accessing the value from Another Sum.
const res1 = Sum().concat(Sum()).concat(Sum());
console.log(res1); // Sum 25
All / Any:
Boolean in JS is not a semigroup type, we can make it so by introduces 'All & Any' semigroup type:
// All :: All s => b -> s b
const All = x => ({
x,
concat: ({x: y}) => All(y && x),
inspect: () => `All ${x}`
});
// Any :: Any s => b -> s b
const Any = x => ({
x,
concat: ({x: y}) => Any( y || x),
inspect: () => `Any ${x}`
})
const res2 = All(false).concat(All(true));
const res23 = Any(false).concat(Any(true));
console.log(res2) // All false
console.log(res3) // Any true
First:
Wcan define a semigroup type for any other Object in JS, which only return the First one, ignore the rest:
// First :: First f => a -> f a
const First = x => ({
x,
concat: (_) => First(x),
inspect: () => `First ${x}`
}) const res3 = First('a').concat(First()).concat(First());
console.log(res3) // 'a'
Map:
Object in JS don't have 'concat' method, of course you can use some libs such as https://github.com/DrBoolean/immutable-ext
But here, we will define a simple version of Map by ourselves. Which loop though each props of the given object, apply concat method for each prop:
// Map :: Map m => a -> m a
const Map = x => ({
x,
concat: ({x: y}) => Object.keys(y).map(k => y[k].concat(x[k]))
});
Let take a example to see how those semigroup types can be useful:
For example we have to object, we want to 'concat' them, by concat, I mean, for the name prop, we just want to keep the First one, for the 'isPaid' prop we want to take 'All' operation, for 'points' we want to take 'Sum' operation, for 'friends', you guess so... 'concat' operation.
const _acct1 = {name: 'Nico', isPaid: true, points: , friends: ['Franklin']};
const _acct2 = {name: 'Nico', isPaid: false, points: , friends: ['Gatsby']};
So the final result should be:
// [ Nico, false, 40, [ 'Gatsby', 'Franklin' ] ]
First, let's apply the Semigroup types we already have to those two objects:
const acct1 = {name: First('Nico'), isPaid: All(true), points: Sum(), friends: ['Franklin']};
const acct2 = {name: First('Nico'), isPaid: All(false), points: Sum(), friends: ['Gatsby']};
OK, now we need to concat 'acct1' and 'acct2', but Object doesn't have 'concat' method as we discussed before, therefore we need to wrap our objects into 'Map':
const acct1 = Map({name: First('Nico'), isPaid: All(true), points: Sum(), friends: ['Franklin']});
const acct2 = Map({name: First('Nico'), isPaid: All(false), points: Sum(), friends: ['Gatsby']});
Now we can call:
const res4 = acct1.concat(acct2);
console.log(res4); // [ First Nico, All false, Sum 40, [ 'Gatsby', 'Franklin' ] ]
OK, that's it. The end of Semigroup...
Below I append a better version:
const R = require('ramda'); // Sum :: Sum s => a -> s a
const Sum = x => ({
x,
concat: ({x: y}) => Sum(x + y),
inspect: () => `Sum ${x}`
})
const res1 = Sum().concat(Sum()).concat(Sum());
console.log(res1); // {x: 25} // All :: All s => b -> s b
const All = x => ({
x,
concat: ({x: y}) => All(y && x),
inspect: () => `All ${x}`
});
// Any :: Any s => b -> s b
const Any = x => ({
x,
concat: ({x: y}) => Any( y || x),
inspect: () => `Any ${x}`
})
const res2 = All(false).concat(All(true));
console.log(res2) // All false // First :: First f => a -> f a
const First = x => ({
x,
concat: (_) => First(x),
inspect: () => `First ${x}`
}) const res3 = First('a').concat(First()).concat(First());
console.log(res3) // 'a' const _acct1 = {name: 'Nico', isPaid: true, points: , friends: ['Franklin']};
const _acct2 = {name: 'Nico', isPaid: false, points: , friends: ['Gatsby']}; // Map :: Map m => a -> m a
const Map = x => ({
x,
concat: ({x: y}) => Object.keys(y).map(k => y[k].concat(x[k]))
});
const transformations = R.evolve({
name: First,
isPaid: All,
points: Sum
});
const semi_transform = R.compose(
Map,
transformations
);
const acct1 = semi_transform(_acct1);
const acct2 = semi_transform(_acct2);
const res4 = acct1.concat(acct2);
console.log(res4); // [ First Nico, All false, Sum 40, [ 'Gatsby', 'Franklin' ] ]
[Functional Programming] Write simple Semigroups type的更多相关文章
- [Functional Programming] From simple implementation to Currying to Partial Application
Let's say we want to write a most simple implementation 'avg' function: const avg = list => { let ...
- [Functional Programming] Compose Simple State ADT Transitions into One Complex Transaction
State is a lazy datatype and as such we can combine many simple transitions into one very complex on ...
- Functional Programming without Lambda - Part 2 Lifting, Functor, Monad
Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...
- Functional Programming without Lambda - Part 1 Functional Composition
Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...
- a primary example for Functional programming in javascript
background In pursuit of a real-world application, let’s say we need an e-commerce web applicationfo ...
- Monad (functional programming)
In functional programming, a monad is a design pattern that defines how functions, actions, inputs, ...
- Beginning Scala study note(4) Functional Programming in Scala
1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...
- Functional programming
In computer science, functional programming is a programming paradigm, a style of building the struc ...
- BETTER SUPPORT FOR FUNCTIONAL PROGRAMMING IN ANGULAR 2
In this blog post I will talk about the changes coming in Angular 2 that will improve its support fo ...
随机推荐
- JavaScript with JSONPath
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JavaScript JSO ...
- React Native 系列(七)
前言 本系列是基于React Native版本号0.44.3写的.几乎所有的App都使用了ListView这种组件,这篇文章将学习RN中ListView的平铺样式和分组样式. ListView平铺样式 ...
- 【BZOJ 1016】 1016: [JSOI2008]最小生成树计数 (DFS|矩阵树定理)
1016: [JSOI2008]最小生成树计数 Description 现在给出了一个简单无向加权图.你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的最小生成树.(如果两颗最小生成树 ...
- BZOJ4554 HEOI2016游戏
网络流. 我一开始傻傻的将每条边与每一列连边,边权为联通块树,但是这样做是错的因为我们就在跑网络流中会忽略掉边和列的关系. 我们在做网络流题时一定要注意题目中给出的限制条件,一定要以限制条件建图!!! ...
- 【20181027T2】易水决【贪心+堆】
原题:loj6035 [错解] 全肝T1了没怎么想 [正解] 一眼贪心 先考虑\(b_i=0\)怎么做 可以模拟一个正常人的思维 开一个堆,记录每个任务需要的时间(包括等待),每次从中取出一个任务,表 ...
- 【转】_CrtSetBreakAlloc 内存泄漏
声明:本内容转载自 https://my.oschina.net/gp8wLHNUeKd2C/blog/110707 在使用VS开发过程中,(今日)遇到内存泄漏的情况.具体表现为: 在输出窗口中,显示 ...
- QTP 10 破解 之路
1.下载QTP 10 安装包 2.破解软件(mgn-mqt82.exe) (阿里云云主机里执行不了,一执行CPU就99%,也没有生成lservrc) 手动创建C:\Program Files (x8 ...
- 图解linux内核编译框架
内核是如何编译成的 -知其然而不知其所以然 (第一篇) 转载:http://blog.chinaunix.net/uid-28236237-id-3840137.html Linux内核有分门别类的目 ...
- 了解你的Linux系统:必须掌握的20个命令
转载:http://blog.chinaunix.net/uid-16459552-id-3877787.html 要想详细了解你的Linux系统,为系统评估和性能调化提供准确的信息,那么,你会经常用 ...
- spring-cloud服务器雪崩效应
在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用.为了保证其高可用,单个服务 ...