DEV Community

Discussion on: Go is my gateway drug

Collapse
 
peteraba profile image
Peter Aba

Here's an improved version from the F# community:

module Hamming

let distance (strand1: string) (strand2: string): int option =
    if strand1.Length = strand2.Length
    then
        Some(Seq.fold2 (fun acc a b -> if a = b then acc; else acc + 1) 0 strand1 strand2)
    else None
Enter fullscreen mode Exit fullscreen mode
Collapse
 
piaste profile image
piaste

We can do even better :)

1) Strings implement IEnumerable, so they can be treated as a sequence of characters
2) Zip functions like Python's exist in F#'s Seq module as well
3) 'Count how many elements of a sequence fulfill this condition' can be done in easier ways than with an explicit folding. Seq.length, Seq.countBy, Seq.sumBy are all functions that can do the job.

Put it together, and you can do it like this:

let distance s1 s2 = 
  if String.length s1 <> String.length s2 then None
  else
    Seq.zip s1 s2
    |> Seq.sumBy (fun (c1, c2) -> if c1 <> c2 then 1 else 0)
    |> Some
Collapse
 
peteraba profile image
Peter Aba

I'll update the post with this, thanks a lot! Would you sharing your thoughts on some more code here? dev.to/peteraba/fp-public-review-1...