Skip to content

Instantly share code, notes, and snippets.

@kyleheadley
kyleheadley / inherit.rs
Created January 4, 2018 03:21
A model for trait-based inheritance in Rust
//! Demo of static "inheritance"
//!
//! Use trait objects to get dynamic inheritance,
//! but casting to a subtype is not explored here
////////////////////////////////////////////////////////
// Define Base type, interface, and what is overloadable
////////////////////////////////////////////////////////
/// The main type that will be extended
@kyleheadley
kyleheadley / functor.rs
Last active February 21, 2018 17:40
An implementation in Rust of the examples from the OCaml manual chapter on modules and funtors
//! This file is a translation of the example code in the OCaml manual
//! chapter two,"The module system", into Rust code.
//!
//! The intent is to translate as directly as possible, to show OCaml
//! users a way to implement their functionality. This means that
//! later, more complex sections are neither idiomatic Rust nor a
//! perfect translation of the OCaml. Further study would be required,
//! but hopefully this helps explain some of the concepts.
//!
//! There are two constructs in Rust that might match OCaml modules,
@kyleheadley
kyleheadley / as_trait.rs
Last active April 1, 2018 17:27
Demonstration of casting to multiple trait objects
use std::thread;
use std::sync::Arc;
use std::sync::RwLock;
struct Wrap{one:usize,zero:usize}
trait WriteIt {
fn write1(&mut self,w:usize);
fn read1(&self) -> usize;
}
@kyleheadley
kyleheadley / hkt_tree.rs
Last active March 18, 2020 17:13
demo a struct that can be used with Rc or Arc pointer types
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;
trait PtrFunc<A> {type Ptr:Sized+Clone+Deref+From<A>;}
struct RcPtr;
impl<A> PtrFunc<A> for RcPtr {type Ptr = Rc<A>;}
struct ArcPtr;
impl<A> PtrFunc<A> for ArcPtr {type Ptr = Arc<A>;}
@kyleheadley
kyleheadley / traitlang.rs
Created November 14, 2018 17:22
Example of typed functional programming in Rust's type-level language
trait Nat {}
struct Zero;
impl Nat for Zero {}
struct Succ<N>(N);
impl<N:Nat> Nat for Succ<N> {}
type One = Succ <Zero >;
trait AddOne : Nat { type Result:Nat; }
impl<N:Nat> AddOne for N { type Result = Succ<N>; }
@kyleheadley
kyleheadley / trati-dsl.rs
Created November 14, 2018 17:24
A lambda DSL embedded in Rust
#![allow(unused)]
// Meta values and functions
// -------------------------
// Bool values
struct False;
struct True;
// Option values