Is an explicit transfer type not equivalent to type inference (in terms of expressiveness)?

I am trying to translate traverse/ sequenceAinto Javascript. Now the following Haskell implementation behavior gives me problems:

traverse (\x -> x) Nothing -- yields Nothing
sequenceA Nothing -- yields Nothing
traverse (\x -> x) (Just [7]) -- yields [Just 7]
sequenceA (Just [7]) -- yields [Just 7]

As a newbie to Haskell, I wonder why the first expression works at all:

instance Traversable Maybe where
    traverse _ Nothing = pure Nothing
    traverse f (Just x) = Just <$> f x

pure Nothingshould not work in this case, since there is no minimal application context in which the value can be placed. It seems that the compiler lazily checks the type of this expression and since the mapping of the id function over Nothingis noop, it simply “skips” the type error, so to speak.

Here is my Javascript translation:

( , , Javascirpt , , CH .)

// minimal type system realized with `Symbol`s

const $tag = Symbol.for("ftor/tag");
const $Option = Symbol.for("ftor/Option");

const Option = {};

// value constructors (Church encoded)

const Some = x => {
  const Some = r => {
    const Some = f => f(x);
    return Some[$tag] = "Some", Some[$Option] = true, Some;
  };

  return Some[$tag] = "Some", Some[$Option] = true, Some;
};

const None = r => {
  const None = f => r;
  return None[$tag] = "None", None[$Option] = true, None;
};

None[$tag] = "None";
None[$Option] = true;

// Traversable

// of/map are explicit arguments of traverse to imitate type inference
// tx[$Option] is just duck typing to enforce the Option type
// of == pure in Javascript

Option.traverse = (of, map) => ft => tx =>
 tx[$Option] && tx(of(None)) (x => map(Some) (ft(x)));

// (partial) Array instance of Applicative

const map = f => xs => xs.map(f);
const of = x => [x];

// helpers

const I = x => x;

// applying

Option.traverse(of, map) (I) (None) // ~ [None]
Option.traverse(of, map) (I) (Some([7])) // ~ [Some(7)]

, Haskell, [None], None. , , , .

  • ?
  • , ( )?
+4
1

GHCi . unconstrained Applicative to IO, GHCi ( .hs).

> :t pure Nothing
pure Nothing :: Applicative f => f (Maybe b)

> pure Nothing
Nothing

javascript ; Applicative , .

+4

Source: https://habr.com/ru/post/1679133/


All Articles