Skip to content

Instantly share code, notes, and snippets.

@will-molloy
Last active December 22, 2019 02:33
Show Gist options
  • Save will-molloy/73438bd81632bfb2fe5c3233519a0fe0 to your computer and use it in GitHub Desktop.
Save will-molloy/73438bd81632bfb2fe5c3233519a0fe0 to your computer and use it in GitHub Desktop.
Pattern matching in Haskell (and how it may look in future version of Java)
allTrue :: [Bool] -> Bool
allTrue [] = True
allTrue (head:tail) = head && allTrue tail
anyTrue :: [Bool] -> Bool
anyTrue [] = False
anyTrue (head:tail) = head || anyTrue tail
noneTrue :: [Bool] -> Bool
noneTrue = not . anyTrue
main :: IO()
main = do
print $ allTrue [True, True, True] -- True
print $ allTrue [True, True, False] -- False
print $ anyTrue [False, True, False] -- True
print $ anyTrue [False, False, False] -- False
print $ noneTrue [False, False, False] -- True
print $ noneTrue [True, False, False] -- False
static boolean allTrue(List<Boolean> list) {
return match list {
case list.isEmpty() -> true;
default -> list.get(0) && allTrue(list.subList(1, list.size()));
}
}
static boolean anyTrue(List<Boolean> list) {
return match list {
case list.isEmpty() -> false;
default -> list.get(0) || anyTrue(list.subList(1, list.size()));
}
}
static boolean noneTrue(List<Boolean> list) {
return !anyTrue(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment