sanctuary-js / sanctuary

:see_no_evil: Refuge from unsafe JavaScript
https://sanctuary.js.org
MIT License
3.03k stars 94 forks source link

How to create a function in 'sanctuary'? #678

Closed lsby closed 4 years ago

lsby commented 4 years ago

Hi, I really like this project and it's very exciting. Although it lacks some introductory material.

I checked the documentation for "sanctuary" and "sanctuary-def". I noticed that in "sanctuary-def", I can use the function "def" returned by "$ .create" to define a new function.

But in "sanctuary", there is an example of using a document:

  const {create, env} = require ('sanctuary');
  ...
  const S = create ({
    checkTypes: process.env.NODE_ENV !== 'production',
    env: env.concat ([IdentityType ($.Unknown)]),
  });

Where "S" is not the "def" in "sanctuary-def". "S.def" also does not exist.

I checked the "sanctuary" source code.

  function create(opts) {
    var def = $.create (opts);
    var S = {
      env: opts.env,
      is: def ('is') ({}) ([$.Type, $.Any, $.Boolean]) ($.test (opts.env)),
      Maybe: Maybe,
      Nothing: Nothing,
      Either: Either
    };
    (Object.keys (_)).forEach (function(name) {
      S[name] = def (name) (_[name].consts) (_[name].types) (_[name].impl);
    });
    S.unchecked = opts.checkTypes ? create ({checkTypes: false, env: opts.env})
                                  : S;
    return S;
  }

The "def" obtained did not appear to be exposed.

So how do I define my own functions in a "sanctuary"?

davidchambers commented 4 years ago

Hello, @lsby, and welcome to the Sanctuary community. :wave:

I noticed that in "sanctuary-def", I can use the function "def" returned by "$ .create" to define a new function.

That's the way to do it. :)

So how do I define my own functions in a "sanctuary"?

Sanctuary itself does not provide this functionality; you need to depend on sanctuary-def. If you are using Sanctuary in your project, depending on sanctuary-def directly will not affect your bundle size as it is already a transitive dependency.

Here is a minimal example:

const $ = require ('sanctuary-def');

const def = $.create ({checkTypes: true, env: $.env});

//    greet :: String -> String
const greet =
def ('greet')
    ({})
    ([$.String, $.String])
    (name => `Hello, ${name}!`);
lsby commented 4 years ago

@davidchambers , I get it now, thanks!