Created
July 31, 2012 00:13
-
-
Save SamirTalwar/3212228 to your computer and use it in GitHub Desktop.
Detecting whether two strings are anagrams, in Haskell.
This file contains hidden or 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
| import Data.List | |
| import Test.QuickCheck | |
| anagrams :: String -> String -> Bool | |
| anagrams x y = sort x == sort y | |
| main = do | |
| quickCheck (\(x, y) -> length x <= 8 ==> anagrams x y == (y `elem` permutations x)) | |
| -- tests `anagrams` using 100 sets of 2 random strings | |
| -- uses an obvious but painfully slow algorithm | |
| -- discards any test string longer than 8 characters as generating the permutations takes forever |
Author
Yeah, you could knock up the number of tries. Honestly, in a real
system, I would have normal unit tests along with the QuickCheck
tests. They're not great on their own, but they're brilliant at
catching edge-cases.
— Samir.
…On 1 Aug 2012, at 10:31, Tom Denley ***@***.*** wrote:
Aren't the chances that 100 random pairs of strings contain a pair that are an anagram of each other vanishingly small?
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/3212228
I'm aware this was posted a while ago, but here is an addition; a case-insensitive version. I'm not very experienced so I wonder if this could be more concise
module AnagramDetection where
import Data.Char(toLower)
import Data.List
isAnagramOf :: String -> String -> Bool
isAnagramOf test original = sort (lower test) == sort (lower original)
lower :: String -> String
lower "" = ""
lower (a:as) = toLower a : lower as
Author
Your lower function could just be implemented as map toLower.
I think the tersest solution I can think of looks something like this:
import Data.Char (toLower)
import Data.Function (on)
import Data.List (sort)
...
isAnagramOf = (==) `on` (sort . map toLower)This is the equivalent of:
isAnagramOf a b = sort (map toLower a) == sort (map toLower b)Didn't expect such a quick response, but -- AAAAAHHHH So that's how you map a function, I tried map toLower but actually wasn't placing the parentheses properly; so my newb self just applied an extra function.
Thank you for the response and explanation!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aren't the chances that 100 random pairs of strings contain a pair that are an anagram of each other vanishingly small?