Skip to content

Instantly share code, notes, and snippets.

@orende
Created January 9, 2024 09:27
Show Gist options
  • Save orende/3b97c49063bee8533e47951ae78c54de to your computer and use it in GitHub Desktop.
Save orende/3b97c49063bee8533e47951ae78c54de to your computer and use it in GitHub Desktop.
Functional programming patterns in Rust
#![allow(non_snake_case)]
use derive_builder::Builder; // cargo add derive_builder
use std::time::{SystemTime, Duration};
/// A pure function to reverse a string.
fn reverseString(input: &str) -> String {
let idxs = input.char_indices().rev();
let mut output = String::new();
for (_,c) in idxs {
output.push(c);
}
output
}
/// A function using recursion to general factorial numbers.
fn factorial(input: i32) -> i32 {
if input > 0 {
return input * factorial(input-1)
} else {
return 1
}
}
#[derive(Default, Builder, Debug)]
#[builder(setter(into))]
struct Person {
name: String,
#[builder(default = "18")]
age: u8,
}
fn main() {
const SUFFIX: &str = "!";
let greeterFn = |i: usize| -> String { format!("Hello{}", SUFFIX.repeat(i)) };
println!("{}", greeterFn(4)); // prints: Hello!!!!
println!("{}", reverseString("hello world")); // prints: dlrow olleh
// all variables are immutable, unless prefixed by the "mut" keyword
let _myVar = 1;
let mut _myMutableVar = 2;
// the builder pattern lets us immutably create objects
let person = PersonBuilder::default().name("Test Person").build().unwrap();
println!("{:?}", person);
let optionalA = Option::Some(123);
let optionalB: Option<i32> = Option::None;
println!("Optional A: {}", optionalA.unwrap_or(0));
println!("Optional B: {}", optionalB.unwrap_or(0));
let myList: [usize; 10] = core::array::from_fn(|i| i + 1);
let sumOfEvenNumbers = myList.into_iter()
.map(|i| i*2)
.filter(|i| i%2==0)
.reduce(|acc, el| acc + el)
.unwrap_or(0); // reduce returns an optional, so we default to 0 if it's empty
println!("Sum of even numbers: {sumOfEvenNumbers}"); // prints: 110
println!("Factorial of {} is {}", 5, factorial(5));
let num = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs();
let pair = (num, num%2==0);
match pair {
(i, false) => println!("{i} is an odd number"),
(i, true) => println!("{i} is an even number"),
}
let add3Fn = curry(3);
println!("10 + 3 = {}", add3Fn(10)); // prints: 10 + 3 = 13
}
fn curry(i: i32) -> impl Fn(i32) -> i32 {
move |j: i32| j+i
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment