Last active
December 22, 2019 02:33
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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