Skip to content

Instantly share code, notes, and snippets.

@JoeyEremondi
Last active September 9, 2016 02:16
Show Gist options
  • Save JoeyEremondi/5d6dd10507a42bbd8e8c0d5e23a5514d to your computer and use it in GitHub Desktop.
Save JoeyEremondi/5d6dd10507a42bbd8e8c0d5e23a5514d to your computer and use it in GitHub Desktop.
use std::rc::Rc;
enum List<T> {
Null,
Cons(Rc<T>, Rc<List<T>>),
}
fn map_uncurried<A, B, F>(f: Rc<F>, lst: Rc<List<A>>) -> Rc<List<B>>
where F: Fn(Rc<A>) -> Rc<B>
{
match (*lst) {
List::Null => Rc::new(List::Null),
List::Cons(ref h, ref t) => {
let newHead = f.clone()(h.clone()) ;
let newTail = map_uncurried(f.clone(), t.clone()).clone() ;
Rc::new(List::Cons(newHead, newTail) )
}
}
}
fn map_borrow<A, B, F>(f: &F, lst: Rc<List<A>>) -> Rc<List<B>>
where F: Fn(Rc<A>) -> Rc<B>
{
match (*lst) {
List::Null => Rc::new(List::Null),
List::Cons(ref h, ref t) => {
let newHead = f(h.clone()) ;
let newTail = map_borrow(f, t.clone()).clone() ;
Rc::new(List::Cons(newHead, newTail) )
}
}
}
fn add_n(n : i32) -> Rc<Fn(i32) -> i32 + 'static> {
Rc::new(move |x| n + x)
}
fn map_curried<A,B,F, R>(f : Rc<F>) -> Box<Fn(Rc<List<A>>) -> Rc<List<B>> + 'static>
where F: Fn(Rc<A>) -> Rc<B> + 'static,
{
Box::new( move |lst: Rc<List<A>>| map_uncurried(f.clone(),lst.clone()))
}
fn main() {
let square = map_curried(Rc::new(|x: i32| x * 2));
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment