Exploring Haskell: Confusion with Inverse Function and Recursion

I just started learning Haskell, and I'm trying to write a simple function that takes a list of strings and changes each line in a list:

revComp :: [String] -> [String]
revComp [] = []
revComp [x] = [] ++ [reverse x]
revComp (x:xs) = revComp [xs]

When I try to load my code into GHCI, I get an error message:

Couldn't match expected type `Char' with actual type `[Char]'
Expected type: String
Actual type: [String]

Can someone explain what and where is my problem? Many thanks.

+5
source share
4 answers

The first three lines are fine. Your type signature is correct, the second line is correct, and the third. (However, the [] ++ [reverse x]same as [reverse x].)

, , . x , : revComp [xs] revComp , xs . x - , xs - . , xs [String], [xs] [[String]], revComp [String]! x .

revComp xs, , (:), ( , x:xs, ). , . , , [x] - x:[].

+9

ehird , - - "/" , . map to reverse:

Prelude> let revComp = map reverse
Prelude> revComp ["olleh", "dlrow"]
["hello","world"]

revComp :: [[a]] -> [[a]] ( [String] -> [String], map reverse ), reverse , .

+6

The third line may not be necessary even with your example. An edge (termination condition) can only be an empty list. You can skip the condition for one item.

revComp :: [String] -> [String]
revComp [] = []
revComp (x:xs) = reverse x : revComp xs

I do not know if the term CS exists for this. Someone in the community may add this information.

+4
source

A few more ways to do the same thing:



    revstr [] = []
    revstr (x:xs) = reverse x : revstr xs

    revstr2 [] = []
    revstr2 (x:xs) = [reverse x] ++ revstr2 xs

    revstr3 xs = map reverse xs
    revstr4 = map reverse       -- map takes 2 arguments ;)

    revstr5 xs = foldl step [] xs
     where step acc x = acc ++ [reverse x]

    revstr6 xs = foldr step [] xs
     where step x acc = reverse x : acc
+1
source

All Articles