Skip to content

Instantly share code, notes, and snippets.

@SamirTalwar
Created July 31, 2012 00:13
Show Gist options
  • Select an option

  • Save SamirTalwar/3212228 to your computer and use it in GitHub Desktop.

Select an option

Save SamirTalwar/3212228 to your computer and use it in GitHub Desktop.
Detecting whether two strings are anagrams, in Haskell.
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
@scarytom
Copy link

scarytom commented Aug 1, 2012

Aren't the chances that 100 random pairs of strings contain a pair that are an anagram of each other vanishingly small?

@SamirTalwar
Copy link
Author

SamirTalwar commented Aug 1, 2012 via email

@indiscrete-mathematics
Copy link

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

@SamirTalwar
Copy link
Author

SamirTalwar commented Dec 19, 2021

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)

@indiscrete-mathematics
Copy link

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