Reputation: 865
I'm a complete noob to Haskell I cant get my code working at all and i have no clue on how to fix it! I need help :) If someone has an idea of where i need to look in order to fix my issue i would be extremly greatful for ideas and nudges in the right direction.
I am trying to create a type of C# string.Format that repeats until a list is finished. The list is created by the userinput and then i just want a string to be repeated untill the list is finished.
test :: Integer -> String
let list_n [0..k]
test k = putStrLn (r * r) | r <- list_n --My idea here is that i am forcing
--the entire list onto r and making it repeated as long as there is more in the
--list, But im not even sure that is possible :(
Anyone has a better idea on how to do this? I want all the results in a line and not a row therefore im trying to create ittereration but in HaskeLL that is easier said then done :/
Upvotes: 2
Views: 6149
Reputation: 32455
Maybe you mean to print a given string n
times, and you appear to want to start a newline with each string, and you seem to want to use a list comprehension, which would be
test :: Integer -> String -> IO ()
test n xs = sequence_ [putStrLn xs| i<- [1..n]]
but you'd be throwing away the integers i
you calculated. You'd be better to do
test n xs = replicateM_ n (putStrLn xs)
which gives
Main> test 3 "Hello"
Hello
Hello
Hello
Perhaps you meant to show the numbers themselves as strings, which would be
test n = sequence_ [putStrLn (show i)| i<- [1..n]]
but again, it would be nicer to do
test n = mapM_ putStrLn (map show [1..n])
These two give
Main> test 3
1
2
3
But mainly, what you need to do is follow a good introductory text first. I'd recommend Learn You a Haskell for Great Good.
It would help enormously if you edited your question to make it clearer what you wanted. What output did you want?
Upvotes: 3
Reputation: 52049
Here is something that is closer to the imperative style:
import Control.Monad (forM_)
test :: Int -> IO ()
test n = forM_ [0..n] (\i -> putStrLn $ show $ i*i)
This translates roughly into: "for each i in [0..n], do ..."
Upvotes: 3
Reputation: 153102
Here are two proposals; one tries to match the code you posted, and the other tries to match the English you posted. This seems to be mostly a question about syntax, so I'm not sure there's a lot of meaningful explanation that can go along with this other than "read a tutorial".
-- match the code
test :: Int -> String
test k = concat [show (r * r) | r <- [0..k]]
-- match the English
test :: Int -> String -> String
test k s = concat [s | r <- [0..k]]
Upvotes: 6