0

I am new to F#. This is my first functional programming language.

I would like to write an algorithm to calculate the Hamming distance between two strings of equal length. How would one do so in F#? Any examples consisting of pseudocode would be greatly appreciated.

2 Answers 2

8

You can use Seq.map2 to compare corresponding values then sum the differences:

let hamming s1 s2 = Seq.map2((=)) s1 s2 |> Seq.sumBy(fun b -> if b then 0 else 1)
1
  • That's a very nice solution!
    – oopbase
    Mar 13, 2015 at 13:01
3

Maybe consider this http://davefancher.com/tag/hamming-distance/? Or is there any particular reason that it is not meeting your requirements? From the linked page:

let hammingDistance (source : string) (target : string) =
  if source.Length <> target.Length then failwith "Strings must be equal length"

  Array.zip (source.ToCharArray()) (target.ToCharArray())
  |> Array.fold (fun acc (x, y) -> acc + (if x = y then 0 else 1)) 0

hammingDistance "abcde" "abcde" |> printfn "%i" // 0
hammingDistance "abcde" "abcdz" |> printfn "%i" // 1
hammingDistance "abcde" "abcyz" |> printfn "%i" // 2
hammingDistance "abcde" "abxyz" |> printfn "%i" // 3
hammingDistance "abcde" "awxyz" |> printfn "%i" // 4
hammingDistance "abcde" "vwxyz" |> printfn "%i" // 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.