Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `.of` Constructor on Sanctuary Maybe

I'm working through a tutorial on functional programming that shows the following code example using the sanctuary.js library:

var S = require('sanctuary')
var Maybe = S.Maybe

S.add(
  Maybe.of(3)
  ,Maybe.of(5)
)
.map(n => n * n)

I get the error Maybe.of is not a function. The sanctuary.js API documentation shows an example of using .of as S.of(S.Maybe, 42), so I modified my code like this:

...
S.of(S.Maybe, 3)
,S.of(S.Maybe, 5)

And I get the error:

add :: FiniteNumber -> FiniteNumber -> FiniteNumber
       ^^^^^^^^^^^^
            1

The value at position 1 is not a member of ‘FiniteNumber’.

I don't see any documentation on the sanctuary site about the FiniteNumber type class. How do I make this code work? And is there any way to chain the sanctuary .of constructor onto type classes, so the example on the tutorial site works?

like image 972
webstackdev Avatar asked Nov 26 '17 22:11

webstackdev


2 Answers

You cannot add two Maybes, you can only add two numbers. Notice that the tutorial you read uses add = R.lift(R.add).

In sanctuary, you can use

S.lift2(S.add, S.Just(3), S.Just(5)) // Just(8)

or

S.ap(S.map(S.add, S.Just(3)), S.Just(5)) // Just(8)
S.Just(3).map(S.add).ap(S.Just(5)) // Just(8)

or

S.ap(S.ap(S.Just(S.add), S.Just(3)), S.Just(5)) // Just(8)
S.Just(S.add).ap(S.Just(3)).ap(S.Just(5)) // Just(8)
like image 84
Bergi Avatar answered Sep 20 '22 15:09

Bergi


For wrapping some value to Maybe you should use function S.toMaybe instead Maybe.of

like image 27
Roman Valihura Avatar answered Sep 22 '22 15:09

Roman Valihura