'How can I go through a list of numbers and compare it with an another list I am going through?
I want to input two strings, "Hello" and "Hi" for example, and I want to go through every element in the two strings simultaneously and compare every character one by one. The two strings length in the actual program should be 5, if a char is equal to the other, return true, otherwise return false.
The program I have in mind should see 'H' in "Hello" and 'H' from "Hi" and return true, then I want it to check the 'e' in "Hello" and the 'i' in "Hi" and return false. I want it to keep on doing that till there is nothing to compare. I think I might need to use recursion but I am not sure how to implement it in this program really.
I tried using x:xs with the maximum range of 5 so [0..5], but it didn't work at all.
My code (not working):
uncurryingString :: String -> Int -> Char
uncurryingString a b = a !! b
match :: String -> String -> [Int] -> Bool
match a b (x:xs)
| uncurryingString a [x+1 | x <- xs] == uncurryingString b [x+1 | x <- xs] = True
| otherwise = False
Solution 1:[1]
Using a list comprehension is often a good way to compute things in Haskell, but not in this particular case.
I could try this code:
[a==b | a <- "Hello", b <- "Hi"]
What does this do? You might think that this returns True, because the 'H' letters match - or you might thing that this returns False, because the other letters don't match. In fact, it does both - in effect, it is running multiple nested loops.
[True,False,False,False,False,False,False,False,False,False]
So, the takeaway is to use list comprehensions when you want nested loops, or just working through one dataset. Here we just want a single loop that works through the two words in parallel. Hence it must be recursion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Francis King |
