BufBills
BufBills

Reputation: 8103

haskell my last line “putStr" threw error

import Data.List
import Data.Char

isIn :: (Eq a) => [a] -> [a] -> Bool
needle `isIn` haystack = any (needle `isPrefixOf` ) (tails haystack)


encode :: Int -> String -> String
encode offset msg = map (\c -> chr $ ord c + offset) msg

main :: IO()
main =
     if "arts" `isIn` "artsisgood" then 
        putStrLn "is in"
     else
        putStrLn "not in"

     putStr (encode 3 "hey")

My last line makes compiler throw err. What's wrong with it?

Upvotes: 0

Views: 103

Answers (2)

Benesh
Benesh

Reputation: 3428

From your indentation, it seems like you're trying to write in do notation. Just adding the keyword do fixes your code:

main :: IO()
main = do
     if "arts" `isIn` "artsisgood" then 
        putStrLn "is in"
     else
        putStrLn "not in"

     putStr (encode 3 "hey")

Upvotes: 0

Rvion
Rvion

Reputation: 124

2 problems:

  • Indentation was bad for your if statement
  • you didn't chain your 2 operations (see examples below)

Your code fixed:

import Data.List
import Data.Char

isIn :: (Eq a) => [a] -> [a] -> Bool
needle `isIn` haystack = any (needle `isPrefixOf` ) (tails haystack)


encode :: Int -> String -> String
encode offset = map (\c -> chr $ ord c + offset)
-- encode offset msg = map (\c -> chr $ ord c + offset) msg

main :: IO()
main = do
     if "arts" `isIn` "artsisgood" 
       then putStrLn "is in"
       else putStrLn "not in"
     putStr (encode 3 "hey")

main2 =
   if "arts" `isIn` "artsisgood" 
   then putStrLn "is in"
   else putStrLn "not in"
   >> putStr (encode 3 "hey")

Upvotes: 5

Related Questions