Jimmy
Jimmy

Reputation: 11

Haskell function that takes input as a String and returns same sequence of characters in reverse order

The issue is, I am doing:

reverse ("Hello how are you") and getting output as: "uoy era woh olleh" but the expected output is: uoy era woh olleh

Not sure how to remove quotes(") from the above string.

Upvotes: 1

Views: 188

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120731

I assume you're referring to this:

GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /home/sagemuej/.ghci
Loaded GHCi configuration from /home/sagemuej/.ghc/ghci.conf
Prelude> reverse "Hello how are you"
"uoy era woh olleH"

...when actually you would like to have the reply without any quotes around it. Well, GHCi passes all evaluation results through print, which in turn uses the Show typeclass to transform any value into a string – notably, a string that's valid Haskell source code, and could as such be used to recreate the value. (That's extremely useful in prototyping, and it's not limited to strings but can also handle all sorts of other types.)

Now, "uoy era woh olleH" clearly is valid Haskell source code

Prelude> "uoy era woh olleH"
"uoy era woh olleH"

but without the quotes it wouldn't be:

Prelude> uoy era woh olleH

<interactive>:3:1: error:
    Variable not in scope: uoy :: t0 -> t1 -> t2 -> t

<interactive>:3:5: error: Variable not in scope: era

<interactive>:3:9: error: Variable not in scope: woh

<interactive>:3:13: error: Variable not in scope: olleH

that's why GHCi does this. But if you don't want to use the reply as Haskell code, then you also don't need the show wrapper. To just print the raw content of strings, you'll need to explicitly use the IO action whose purpose this is: putStrLn

Prelude> putStrLn $ reverse "Hello how are you"
uoy era woh olleH

(If you don't know what $ is yet: read it as a shorthand notation for putStrLn (reverse "Hello how are you").)

Upvotes: 4

Related Questions