码迷,mamicode.com
首页 > 其他好文 > 详细

[Compose] Isomorphisms and round trip data transformations

时间:2017-01-23 16:38:47      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:format   phi   null   nbsp   ons   apply   filter   val   app   

What is Isomorphisms?
We have a value x, then apply function ‘to‘ and ‘from‘ to value ‘x‘, the result we should still get ‘x‘.

// from(to(x)) == x
// to(from(y)) == y

So Isomorphisms is kind of opreation able to tranform a value back and forward without lose anything.

 

Example1:

const Iso = (to, from) => ({
  to,
  from
}) 

// String <-> [Chat]
const StoC = Iso(
  (str) => str.split(‘‘),
  (chat) => chat.join(‘‘)
);

const res = StoC.from(StoC.to(How));

 

Example2: 

// String <-> [Chat]
const StoC = Iso(
  (str) => str.split(‘‘),
  (chat) => chat.join(‘‘)
);

const truncate = (str, num) => StoC.from(StoC.to(str).slice(0,num)).concat(...);
let res = truncate("Hello World!", 7);
console.log(res); // "Hello W..."

 

Example3:

const Iso = (to, from) => ({
  to,
  from
}) 

// [a] <-> Either/null/a
const singleton = Iso(
  (either) => either.fold(() => [], x => [x]),
  ([x]) => x? Right(x): Left()
)

const filterEither = (e, pred) => singleton.from(singleton.to(e).filter(pred));
const res = filterEither(Right(hello), (x) => x.match(/h/ig))
                .map(x => x.toUpperCase());

 

[Compose] Isomorphisms and round trip data transformations

标签:format   phi   null   nbsp   ons   apply   filter   val   app   

原文地址:http://www.cnblogs.com/Answer1215/p/6344185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!