SimonMeskens / TypeProps

Small library for describing HKTs in TypeScript
Apache License 2.0
32 stars 2 forks source link

Data-type-generic lists sample by Asad Saeeduddin #9

Closed SimonMeskens closed 6 years ago

SimonMeskens commented 6 years ago

@masaeedu

const Arr = (() => {
  const Nil = [];
  const Cons = head => rest => [head, ...rest];
  const match = ({ Cons, Nil }) => a =>
    a.length === 0 ? Nil : Cons(a[0])(a.slice(1));

  return { Nil, Cons, match };
})();

const GenericList = ({ Cons, Nil, match }) => {
  // Misc
  const length = match({ Nil: 0, Cons: _ => rest => 1 + length(rest) });

  // Functor
  const map = f =>
    match({ Nil, Cons: head => rest => Cons(f(head))(map(f)(rest)) });

  return { length, map };
};

console.log(GenericList(Arr).length([0, 1, 2]));
// 3
console.log(GenericList(Arr).map(x => x * 2)([1, 2, 3]));
// [2, 4, 6]

Playground: With TypeProps

SimonMeskens commented 6 years ago

Added playground link with types, you can also find the sample under 'examples/pattern-matching/list.ts'

SimonMeskens commented 6 years ago

@masaeedu, I haven't seen you reply anything, so I'm going to assume this sample is typed correctly and close this. Feel free to ask me to open again if I'm wrong. I know this could potentially use a more generic definition for the nil/cons/match construct that is compatible with the other samples, but I couldn't figure out a way.

masaeedu commented 6 years ago

Sorry, been busy with other stuff. AFAICT the results look good, it's producing number and number[] as it should. I'm afraid I can't be too much help with verifying the correctness of the other stuff.

SimonMeskens commented 6 years ago

That's good enough for now then. I might look into a more generic ADT pattern matcher type later. Just wanted to do some housekeeping :)