Skip to main content
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Tweeted twitter.com/StackCodeReview/status/1399651954700214272
edited tags; edited title
Link
Mast
  • 13.9k
  • 12
  • 57
  • 128

Is it wrong to split this function into Hamming distance between two? strings

Became Hot Network Question
Source Link

Is it wrong to split this function into two?

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.

GHC raises warning: [-Wincomplete-patterns] since my pattern matching in the helper function is incomplete. So:

  1. Is it bad practice to ignore this warning?
  2. Would it be better to implement the recursive part on the Maybe?
  3. 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