Blogger

Delete comment from: Abstract Heresies

Anonymous said...

The C type system is pretty puny, though. In a language with something like typeclasses (e.g. Haskell or Rust) you can constrain the types to the categories you need, with something like

fac :: (Eq a, Num a, Enum a) => a -> a
fac 0 = 1
fac n = n * fac (pred n)

and you can do `fac 54.0` and get `2.308436973392414e71` just fine, but going `fac "a string"` is a compilation error.

Rust _can_ do the same thing, but the constraint gets a lot more verbose and you _do_ have to import some stuff to get arbitrary precision. E.g. running `fac(54.0)` on

fn fac(x: T) -> T
where
____T: Clone + Copy + PartialEq + Sub + Mul + From,
{
____if x == T::from(0) {
________T::from(1)
____} else {
________x * fac(x - T::from(1))
____}
}

will net you an equally precise answer as your lisp example.

You can even add some constraints like making sure the input is non-negative so you don't get into an unending loop at `(factorial -1)`. Good type systems add a lot of power. :)

Apr 11, 2025, 7:26:28 AM


Posted to Why I Program in Lisp

Google apps
Main menu