Using `.of` Constructor on Sanctuary Maybe
Asked Answered
S

2

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?

Symbolism answered 26/11, 2017 at 22:4 Comment(0)
S
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)
Semiliterate answered 26/11, 2017 at 22:38 Comment(2)
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?Symbolism
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.Semiliterate
O
1

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

Ornithorhynchus answered 27/11, 2017 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.