6

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?

webstackdev
  • 850
  • 15
  • 23

2 Answers2

4

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)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    thanks for the help on this and other FP questions I've posted. Can you tell me why I get a "`TypeError: Maybe.of is not a function`" with your first example? I've added `let Maybe = S.Maybe` to prevent a reference error when using `Maybe`, but how do I get it to allow me to chain the sanctuary `of` constructor onto `Maybe` as in your example? – webstackdev Nov 26 '17 at 22:52
  • Oops, I have never actually used Sanctuary. Looks like you indeed need to use `S.of(Maybe, …)` or `S.Just(…)` instead. Or `S.Maybe['fantasy-land/of'](…)`, although I wouldn't recommend that. – Bergi Nov 26 '17 at 23:00
1

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