Skip to content

Instantly share code, notes, and snippets.

@debiru
Created February 15, 2024 11:28
Show Gist options
  • Save debiru/66a38498d95bbf2f2fab8466abba3ab4 to your computer and use it in GitHub Desktop.
Save debiru/66a38498d95bbf2f2fab8466abba3ab4 to your computer and use it in GitHub Desktop.
FizzBuzz-2 in Gleam
import gleam/io
import gleam/int
import gleam/float
import gleam/list
import gleam/result
pub fn main() {
let list = generate_prime_list(100000)
//io.debug(list)
io.debug(list.length(list))
}
fn int_root(n: Int) {
int.square_root(n) |> result.unwrap(0.0) |> float.truncate
}
fn cond_val(cond: Bool, true_value: a, false_value: a) {
case cond { True -> true_value False -> false_value }
}
/// range_step(3, 20, 4) -> [3, 7, 11, 15, 19]
fn range_step(first: Int, last: Int, step: Int) -> List(Int) {
let main = fn () {
let last_diff = last - last / step * step
let over_count = cond_val(first > last_diff, 1, 0) + int.max({ first - last_diff - 1 } / step, 0)
list.range(0, last / step - over_count)
|> list.map(fn (i) { i * step + first })
}
case first <= last {
True -> main()
False -> []
}
}
fn sieve(ints: List(Int)) -> List(Int) {
case ints {
[first, .._] -> ints |> list.filter(fn (i) { i % first != 0 })
_ -> []
}
}
fn recursive_prime_list(primes: List(Int), ints: List(Int), limit: Int) -> List(Int) {
case ints {
[first, .._] -> case first <= limit {
True -> recursive_prime_list(list.concat([primes, [first]]), sieve(ints), limit)
False -> list.concat([primes, ints])
}
_ -> []
}
}
fn generate_prime_list(n: Int) -> List(Int) {
case n {
n, if n < 2 -> []
_ -> list.concat([[2], recursive_prime_list([], range_step(3, n, 2), int_root(n))])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment