Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reserve algorithm is not behaving

Tags:

haskell

The output from running this code is not correct, I cannot wrap my head sadly, to know where the wrong is in my own code. I been staring at it for hours.

Code:

import System.IO(isEOF)

reverseIO :: IO ()
reverseIO = do 
  line <- getLine
  done <- isEOF
  if null line
    then return ()
  else if done then
    putStrLn $ reverseStr line
  else do
      reverseIO

reverseStr :: [w] -> [w]
reverseStr [] = []
reverseStr (x:xs) = reverseStr xs ++ [x]

main = do
  reverseIO

Desired: 2. Reverse and print out.

> hello world
world hello

Running:

GHCi, version 8.10.6: https://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /home/runner/University-Labs/.ghci
[1 of 1] Compiling Main             ( Main.hs, interpreted )
Ok, one module loaded.
 hello world

EDIT: Pressing Ctrl+D,

GHCi, version 8.10.6: https://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /home/runner/University-Labs/.ghci
> hello world
dlrow olleh
like image 211
John Smith Avatar asked May 06 '26 16:05

John Smith


1 Answers

You have to replace replaceStr with unwords . reverse . words:

reverseIO = do 
  line <- getLine
  done <- isEOF
  if null line
    then return ()
  else if done then
    putStrLn . unwords . reverse . words $ line
  else reverseIO
like image 95
BlackBeans Avatar answered May 08 '26 12:05

BlackBeans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!