Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. // First we need to build data structure pair(a, b)
  2. // cons: given a and b, and return a function.
  3. // when you pass cons(a, b) as argument to car, it will return a;
  4. // if you pass it to cdr, it will return b.
  5. const cons = (a, b) => p => p ? a : b;
  6. const car = pair => typeof pair === 'function' ? pair(1) : null;
  7. const cdr = pair => typeof pair === 'function' ? pair(0) : null;
  8.  
  9. // Now we can build list by chaining pair.
  10. // For example, list [1, 2, 3] will be represented as cons(1, cons(2, 3))
  11.  
  12. // Some helper functions, we only implement some basic functions here,
  13. // and it shall be complete enough to build other list operation functions based on it.
  14. const shift = xs => x => cons(x, xs);
  15. const length = xs => typeof xs === 'function' ? 1 + length(cdr(xs)) : 1;
  16. const get = xs => index => index ? get(cdr(xs))(index - 1) : typeof xs === 'function' ? car(xs) : xs;
  17. const concat = (xs, ys) => cdr(xs) == null ? cons(xs, ys) : cons(car(xs), concat(cdr(xs), ys));
  18.  
  19. // Demo time!
  20. const list1 = cons(1, cons(2, 3));
  21.  
  22. length(list1); // 3
  23. get(list1)(0); // 1
  24. get(list1)(1); // 2
  25. get(list1)(2); // 3
  26.  
  27.  
  28. const list2 = shift(list1)(0);
  29.  
  30. length(list2); // 4
  31. get(list2)(0); // 0
  32. get(list2)(1); // 1
  33. get(list2)(2); // 2
  34. get(list2)(3); // 3
  35.  
  36.  
  37. const list3 = concat(cons(2, 4), cons(6, 8));
  38.  
  39. length(list3); // 4
  40. get(list3)(0); // 2
  41. get(list3)(1); // 4
  42. get(list3)(2); // 6
  43. get(list3)(3); // 8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement