Haskell
List comprehensions can use guards to restrict or filter the values produced by earlier generators.
- [x | x <- [1..10], even x]
- The list [2,4,6,8,10] of all numbers x such that x is an element of the list [1..10] and x is even.
If you use a linq list comprehension or comprehension syntax that will be called WHERE.
Using a guard we can define a function that maps a positive integer to its list of factors:
- factors :: Int -> [Int]
- factors n =
- [x | x <- [1..n], n
mod
x ==0] -
factors 15
- [1,3,5,15]
- we can define a function that decides if a number is prime:
- prime :: Int -> Bool
- prime n = factors n == [1,n]
-
prime 15
- False
- define a function that returns the list of all primes up to a given limit:
- primes :: Int -> [Int]
- primes n = [x | x <- [2..n], prime x]
(FP101x)
List
- Praetorian Guard