200 words
1 minutes
240701_for_all_vs_for_some

link#


1. The core idea (logic symbols)|🔝|#

English phraseLogical quantifierSymbol
for someexistential
for alluniversal

2. Formal mathematical meaning|🔝|#

  • 🔹 “For some”

There exists at least one element that satisfies the condition.

xX P(x)\exists_x \in X \ P(x)
  • 🔹 “For all”

Every element must satisfy the condition.

xX P(x)\forall_x \in X \ P(x)

3. Programming intuition (Rust-style)|🔝|#

For some → any()#

let exists = xs.iter().any(|x| x % 2 == 0);
Stop early on FIRST true

For all → all()#

let all = xs.iter().all(|x| x % 2 == 0);
Stop early on FIRST false

4. Rust 코드로 실습|🔝|#

use std::ops::Rem;

fn for_some<T>(x: &[T]) -> bool
where
    T: Copy + Rem<T, Output = T> + PartialEq<T> + From<u8>,
{
    if x.iter().any(|xi| *xi % T::from(2) == T::from(0)) {
        true
    } else {
        false
    }
}

fn for_all<T>(x: &[T]) -> bool
where
    T: Copy + Rem<T, Output = T> + PartialEq<T> + From<u8>,
{
    if x.iter().all(|xi| *xi % T::from(2) == T::from(0)) {
        true
    } else {
        false
    }
}

fn main() {
    let a = vec![1, 2, 3, 4, 5];
    let b = vec![1, 2, 3, 4, 5];
    let is_some = for_some(&a);
    println!("a is some : {is_some}");
    let is_all = for_all(&b);
    println!("b is all : {is_all}");
}
  • result

a is some : true
b is all : false
240701_for_all_vs_for_some
https://younghakim7.github.io/blog/posts/240701_for_all_vs_for_some/
Author
YoungHa
Published at
2024-07-01