this function maps letters onto another letter. Could someone explain to me what does the !! 0
mean here in the function?
findGuess letter guessList
| length guessList == 0 = (letter, letter)
| letter == snd (guessList !! 0) || letter == fst (guessList !! 0) = guessList !! 0
| otherwise = findGuess letter (tail guessList)
CodePudding user response:
(!!)
is the (partial) indexing operator for lists. guessList !! 0
is basically equivalent to head guessList
. Neither is recommended, as they only work when guessList
is not empty. Prefer pattern matching:
findGuess letter [] = (letter, letter)
findGuess letter ((c1, c2):rest) | letter == c1 || letter == c2 = (c1, c2)
| otherwise = findGuess letter rest
As an aside, findGuess
mosty reimplements Data.List.find
:
import Data.List
findGuess letter guessList = case find p guessList of
Nothing -> (letter, letter)
Just x -> x
where p (c1, c2) = letter == c1 || letter == c2
CodePudding user response:
guessList !! 0 is equal to guessList[0] in Java/C#... So, this function check if letter matches the first or second of head pair tuple of the list, after that recursively continue to check all items of list.