Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings differing by only one character

Tags:

string

haskell

So, I'm kinda new to Haskell (and programming generally) and I've been trying to solve a problem for a while. I want to make a function, that has as an input 2 alphanumerics (type String) and that returns True ONLY if both alphanumerics have the same length AND have only 1 different char. So, for example, if the inputs were block and black, I would get True, but if the inputs were black and brake, i would get false. I tried to do this with recursion, but i failed miserably. I need this function, because I wanτ to use it for checking some inputs in a program that I'm working on.

Any help is appreciated, thanks for your time.

like image 580
user1823812 Avatar asked Sep 23 '26 04:09

user1823812


1 Answers

If I understand you right, the different Chars should occur on the same position?

Then I think a straight-forward definition would be:

oneDifferent xs ys = 
   length xs == length ys && 
   1 == length (filter (==False) (zipWith (==) xs ys))

... or ...

oneDifferent xs ys = 
  length xs == length ys &&  
  1 == foldr ((+) . fromEnum) 0 (zipWith (/=) xs ys) where

A recursive solution would be

oneDifferent (x:xs) (y:ys) 
  | x /= y = xs == ys
  | otherwise = oneDifferent xs ys 
oneDifferent _ _ = False   
like image 96
Landei Avatar answered Sep 25 '26 08:09

Landei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!