I wrote this module to find the Hamming distance between two strings. (It’s a problem from
exercism.io‘s Haskell track.)
As I saw it, the problem has two distinct parts: check if the length of the two strings are equal (if not return
Nothing), and recursive pattern matching on equal-length strings.
Since my score is a monad (Maybe), I didn’t know how to implement the recursive adding without dealing with the
Nothing case, so I broke it off into a separate function using a simple Int type.
warning: (-Wincomplete-patterns) since my pattern matching in the helper function is incomplete. So:
- Is it bad practice to ignore this warning?
- Would it be better to implement the recursive part on the Maybe?
- Is there a better way to solve this problem?
I’m very new to Haskell, all help appreciated.
module Hamming (distance) where distance :: String -> String -> Maybe Int distance a b | length a /= length b = Nothing | otherwise = Just $ getDistance a b getDistance :: String -> String -> Int getDistance () () = 0 getDistance (x) (y) = if x == y then 0 else 1 getDistance (x : xs) (y : ys) = getDistance (x) (y) + getDistance xs ys