2 ms·
Pretty hard. The key to this implementation is Haskell's laziness, so you have to implement laziness in Javascript, which will probably not be very ergonomic. Y
by lalaithion 4y ago
Pretty hard. The key to this implementation is Haskell's laziness, so you have to implement laziness in Javascript, which will probably not be very ergonomic. You can write
let loeb = (structure => {
let inner = () => structure.map(item => item(inner()));
return inner;
})
let fs = [ _ => 1
, x => x[0] + 1
, x => x[1] + 1
, x => x[2] + 1
]
console.log(loeb(fs)())
and get an infinite loop, or
let loeb = (structure => {
let inner = () => structure.map(item => item(inner));
return inner;
})
let fs = [ _ => 1
, x => x[0] + 1
, x => x[1] + 1
, x => x[2] + 1
]
console.log(loeb(fs)())
and get [1, null, null, null].
- contravariant 4y agoYou can typically simulate laziness by lifting variables into functions. A 0-arity function works fine, but for lists it's slightly more elegant to define them as functions from an index to a value (in that case the functor map is just composition, which is neat). So the following works let loeb = (structure => { let inner = (i) => structure(i)(inner); return inner; }) let fs = (i) => {switch(i) { case 0: return _ => 1 case 1: return (x) => x(0) + 1 case 2: return (x) => x(1) + 1 case 3: return (x) => x(2) + 1 }} If javascript was sensible you could just do let fs = [ _ => 1 , x => x(0) + 1 , x => x(1) + 1 , x => x(2) + 1 ].at but alas that doesn't work, you can do let fs = (i) => [ _ => 1 , x => x(0) + 1 , x => x(1) + 1 , x => x(2) + 1 ][i] though. In that case javascript may end up rebuilding the list every time, I'm not quite sure.