I’ve just started to learn Haskell and I am trying to write a simple function that takes a list of strings and reverses each string in the list:
revComp :: [String] -> [String]
revComp [] = []
revComp [x] = [] ++ [reverse x]
revComp (x:xs) = revComp [xs]
When I try to load my code in GHCI, I get an error:
Couldn't match expected type `Char' with actual type `[Char]'
Expected type: String
Actual type: [String]
Could anyone explain what and where my problem is? Thanks very much.
The first three lines are fine. Your type signature is correct, the second line is correct, and so is the third. (However,
[] ++ [reverse x]is the same as[reverse x].)The fourth line, however, is wrong. Not only do you not use
xat all on the right-hand side, but you have a type error:revComp [xs]callsrevCompwith a single-element list that hasxsas its only element. Here,xis the first element of the list, andxsis the rest of the list. So, sincexshas the type[String],[xs]has the type[[String]], butrevComptakes a[String]! You want to reversex, and prepend that to the result of reversing the rest of the list.You can use
revComp xsto reverse each string in the rest of the list, and(:)to prepend a value to a list (with the same syntax seen in thex:xspattern you used on the left-hand side). That should be enough information for you to fix the last line. This makes the third line redundant, by the way, since[x]is justx:[].