Skip to content

Instantly share code, notes, and snippets.

View Rudxain's full-sized avatar

Ricardo Fernández Serrata Rudxain

View GitHub Profile
@Rudxain
Rudxain / guard-vs-cond.ts
Last active June 20, 2024 02:18
Type Guards vs. Conditional Types
type numeric = number | bigint
const num_guard = (x: unknown): x is numeric =>
typeof x == 'number' || typeof x == 'bigint'
const num_cond = <T,>(x: T) => (
typeof x == 'number' || typeof x == 'bigint'
) as T extends numeric ? true : false
// this example is incomplete,
pub fn trampoline<F, A, C, T>(f: F, args: A) -> T
where
F: FnOnce(A) -> Result<C, T>,
C: FnOnce() -> Result<C, T>,
{
let mut out = f(args);
// `while let` would require an awkward
// `if let Err(x) return x; unreachable!()` at the end.
// https://users.rust-lang.org/t/is-there-any-way-to-express-while-let-some-true/72527/2
loop {
@Rudxain
Rudxain / safe-combinator!.ts
Last active May 29, 2024 14:45
Perfectly-type-safe tail-recursive factorial with combinator optimization
// boilerplate
class BigUint {
/** Zero */
static N0() {
return new BigUint(0n)
}
/** One */
static N1() {
return new BigUint(1n)
}
@Rudxain
Rudxain / conditional_identity.rs
Last active May 31, 2024 12:16
fns that should be in Rust `core` library (wait, they are! https://doc.rust-lang.org/std/option/enum.Option.html#method.filter)
#![no_std]
/// if `cond` is `true`, then `identity(x)`
///
/// if `cond` is `false` then `drop(x)`
pub fn cond_ident<T>(cond: bool, x: T) -> Option<T> {
if cond {
Some(x)
} else {
None
@Rudxain
Rudxain / divisors.rs
Last active May 18, 2024 23:59
"incomplete" generic impls of proper divisors, in Rust
#![warn(clippy::pedantic, clippy::nursery)]
use core::iter::successors;
use num_integer::{Integer, Roots}; //0.1
pub fn divisors_fast<T: Integer + Roots + Clone>(x: &T) -> Vec<T> {
let sq = x.sqrt();
let mut divs = Vec::new();
let n1 = T::one();
@Rudxain
Rudxain / over-engineered fizz-buzz.rs
Last active May 16, 2024 21:45 — forked from rust-play/playground.rs
My impl of fizz-buzz in purely type-safe Rust
use num_integer::Integer; // 0.1
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum S {
F,
B,
FB,
}
fn fb<T: Integer>(n: &T) -> Option<S> {
@Rudxain
Rudxain / str.len.rs.md
Created May 5, 2024 07:16
How is `&str.len()` defined in Rust?

How does &str have len()?

If str is unsized, then how does a ref magically have a len method? let alone an actual return value?

One could argue "unsized types cannot exist in (safe) Rust. Therefore, an str is just an &str stripped of its size data".

But that explanation doesn't satisfy me

fn main(){let mut n=7usize;while n!=0{print!("{n} ");n=[n*3+1,n/2][n%2]}}
@Rudxain
Rudxain / unnamed-math-mean.py
Created March 25, 2024 21:35
arbitrary way to compute an "average"
def fn(x, n):
return (x/n + x*n) / 2
@Rudxain
Rudxain / termux-is-screen-off
Created October 3, 2023 22:45
Termux polyfills that I rarely use
#!/bin/sh
set -f
[ -n "$(dumpsys deviceidle | grep mScreenOn=false)" ]