classContainer { constructor(x) { this._value = x } // use the of to create the container staticof(x) { returnnewContainer(x) } } Container.of(2) // Container { _value: 2 } Container.of({ name: "jack" }) // Container { _value: { name: 'jack' } }
But we should not directly manipulate the data in the container. We need a function to do this.
1 2 3 4 5 6
// Container.prototype.map :: (a -> b) -> Container a -> Container b Container.prototype.map = function (f) { returnContainer.of(f(this._value)) } let six = Container.of(2).map((x) => x * 3) // Container { _value: 6 } six.map((x) => x.toString()).map((x) =>"number: " + x + "!") // Container { _value: 'number: 6!' }
After passing the values in the Container to the map function, we can let them manipulate it; after the operation is completed, in order to prevent accidents, put them back into the Container they belong to. The result is that we can call the map continuously, running any function we want to run. And the Functor is a container type that implements the map function and adheres to certain rules.
Maybe
In Haskell, the Maybe type is defined as follow:
1
dataMaybe a = Just a | Nothing
Maybe will check if its value is empty before calling the passed function. So let’s create a simple one.
There is a class called Either in scala that represents the value of one of two possible types. Instances of Either are either an instance of Left or Right. Now we need to create the Left and the Right.
// getChange :: a -> b -> Either(String, Number) let getChange = curry((a, b) => { if (a < b) returnLeft.of("You need to give more money.") returnRight.of(a - b) }) getChange(10, 8) // Right { _value: 'Get the change: 2' } getChange(10, 15) // Left { _value: 'You need to give more money.' }
// eigher :: (a -> c) -> (b -> c) -> Either a b -> c var either = curry((f, g, e) => { switch (e.constructor) { caseLeft: returnf(e._value) caseRight: returng(e._value) } }) // faild :: a -> a varfaild = (x) => x // success :: a -> b varsuccess = (x) => { return"get change: " + x } // foo :: a -> a -> c var foo = $.compose(either(faild, success), getChange)
foo(0, 2) // You need to give more money. foo(4, 2) // get change: 2