I am trying to write a function that gets multiple string inputs and terminates on an empty line ('\n') I have following
getLines :: IO [String]
getLines = do x <- getLine
if x == ""
return ()
else do xs <- getLines
return (x:xs)
it fails to compile saying there is something wrong with the if statement
Ideally I want to to work like this
getLines
Apple
Bird
Cat
(enter is pressed)
Output:
["Apple","Bird","Cat"]
You need then after if, and () (empty tuple) should be [] (empty list). In if, the then and else need to be indented as well if they’re on separate lines, because if then else is an operator, and the compiler needs to know that the expression continues. Your indentation needs to be adjusted so that everything is indented more than the leading do:
getLines :: IO [String]
getLines = do x <- getLine
if x == ""
then return []
else do xs <- getLines
return (x:xs)
Or everything is indented more than the line containing the leading do:
getLines :: IO [String]
getLines = do
x <- getLine
if x == ""
then return []
else do
xs <- getLines
return (x:xs)
As a matter of style, you can also use null x instead of x == "".
This is nearly right.
You need a then after your if. You may also need to change the indentation slightly, so that everything is indented as far as the x rather than the do. I think that should just about do it.
Related
I am using the following code in Haskell to get an output of letter combinations.
combinations pre suf letters = prefixed ++ suffixed
where
perms = permutation letters
prefixed = map (\x -> pre ++ x) $ perms
suffixed = map (\x -> x ++ suf) $ perms
I want to import a large textfile like dictonary.txt as a list ["Apple", "Banana.....]" with the structure of:
Apple
Banana
Stawberry
...... and so on
This imported [String] I want to merge with the output [String] of combinations. Somebody who can help me with this?
edit:
To make it more clear. The combinations function gives a output like:
["banana","nanaba,..."] <- All posible combinations of a couple of characters.
I want to merge this list with a list with a list that is created from a txt file (but I dont know ho to import a txt to a list of strings and use it to merge). So the output will be like.
["banana","nanaba,...,Apple,Banana,Strawbery"]
After that it will print the double words in the string.
Another edit with Ankurs code:
combinations pre suf letters = prefixed ++ suffixed
where
perms = permutation letters
prefixed = map (\x -> pre ++ x) $ perms
suffixed = map (\x -> x ++ suf) $ perms
fileLines :: FilePath -> IO [String]
fileLines file = readFile file >>= (\x -> return $ lines x)
main = do
lines <- fileLines "directory.txt"
putStr $ (combinations pre suf letters) ++ lines
I will get a parser error on this one!
:22:22: parse error on input `='
Can someone help me how to order this code? So it dont get anny errors?
fileLines :: FilePath -> IO [String]
fileLines file = readFile file >>= (\x -> return $ lines x)
main = do
lines <- fileLines "directory.txt"
putStr $ show $ (combinations pre suf letters) ++ lines
Ok, so first off, let me clean up your combinations function a little bit:
import Data.List (permutations)
-- Please add type signatures when you ask questions
combinations :: [a] -> [a] -> [a] -> [[a]]
combinations pre suf letters = prefixed ++ suffixed
where
perms = permutations letters
prefixed = map (pre ++) perms
suffixed = map (++ suf) perms
There's no need for the $ and you can use operator sectioning to avoid writing out the lambda.
Next up, your main function needs to read in the lines from the file. This is as simple as:
main = do
ls <- fmap lines (readFile "someFile.txt")
...
Now let's say that you pass your combination function the following arguments:
combinations "foo" "bar" "banana" :: [String]
That leaves you with the following main program:
main = do
ls1 <- fmap lines (readFile "someFile.txt")
let ls2 = combinations "foo" "bar" "banana"
...
Now you need to figure out how to combine ls1 and ls2 into a single list of lines and then print them out or do whatever it is you need to do with that list of lines.
I keep getting an error: couldn't match expected type 'Bool' with actual type '[t0]'. I'm trying to get user inputs of string and then output however many strings in reversed ORDER.
Example input:
HI1
HI2
Example output:
HI2
HI1
My code:
Back :: Int -> IO()
Back x = do line <- sequence_[getLine|[1..x]]
mapM_ print (reverse line)
To expand on Vitus's comment, import Control.Monad, then
back count = do
lines <- replicateM count getLine
mapM_ putStrLn (reverse lines)
If this doesn't work for you, please say what error message you get, or give an example of incorrect output.
In this case, we can forego do notation fairly easily:
back count = mapM_ putStrLn . reverse =<< replicateM count getLine
Or
back count = mapM_ putStrLn =<< liftM reverse (replicateM count getLine)
You may or may not find either of those to be clearer.
Note that your function name must start with a lower case letter, e.g. back. Back as a function name is a syntax error.
Also note that indentation is significant. The indentation of the do block in your question is wrong; the do blocks in my and melpomene's answers are correctly indented.
back :: Int -> IO ()
back x = do line <- sequence [getLine | _ <- [1 .. x]]
mapM_ putStrLn (reverse line)
I'm trying to grab a random item from a string list and save that into another string list but I can't get my code to work.
import System.Random
import Control.Applicative ( (<$>) )
food = ["meatballs and potoes","veggisoup","lasagna","pasta bolognese","steak and fries","salad","roasted chicken"]
randomFood xs = do
if (length xs - 1 ) > 0 then
[list] <- (fmap (xs!!) $ randomRIO (0, length xs -1))
else
putStrLn (show([list])
I'm getting parse error on input '<-' but I'm sure there are more issues then that. There is also the issue that the list may contain the same dishes two days in a row which is not what I want and I guess I can remove duplicates but that also would remove the number of items in the list which I want to stay the same as the number in the list.
Anyone have a good idea how I could solve this? I have been searching for a day now and I can't find something useful for me but that's just because I'm looking in the wrong places. Any suggestion on how I can do this or where I can find the info will be greatly appreciated!
The reason it didn't work is that you needed another do after your if...then. (After a then you need an expression, not a pattern <- expression.)
randomFood :: String -> IO () -- type signature: take a String and do some IO.
randomFood xs = do
if length xs > 1 then do
[list] <- (fmap (xs!!) $ randomRIO (0, length xs -1))
else
putStrLn (show([list])
But that still doesn't compile, because you don't actually do anything with your list.
At the end of every do block, you need an expression to return.
I think you meant to still print some stuff if the length of xs is too short, and you probably meant to print the selected food if there was more than one to choose from.
Better would be:
randomFood :: String -> IO ()
randomFood xs | length xs <= 1 = putStrLn $ show xs
randomFood xs | otherwise = do
item <- (xs!!) <$> randomRIO (0, length xs -1)
putStrLn $ show(item)
This | boolean test = syntax is better for conditional answers based on input.
I changed [list] to item because you're selecting a single item randomly, not a list of items.
Haskell is quite happy to let you put [list], because any string that's got one character in it matches [list].
For example, "h" = [list] if list='h', because "h" is short for ['h']. Any longer string will give you Pattern match failure. In particular, all the food you've specified has more than one character, so with this definition randomFood would never work! item will match anything returned by your randomRIO expression, so that's fine.
You imported <$> then didn't use it, but it's a nice operator, so I've replaced fmap f iothing with f <$> iothing.
I finally realised I'm doing the wrong thing with short lists; if I do randomFood ["lump of cheese"] I'll get ["lump of cheese"], which is inconsistent with randomFood ["lump of cheese"] which will give me "lump of cheese".
I think we should separate the short list from the empty list, which enables us to do more pattern matching and less boolean stuff:
randomFood :: String -> IO ()
randomFood [] = putStrLn "--No food listed, sorry.--"
randomFood [oneitem] = putStrLn . show $ oneitem
randomFood xs = do
item <- (xs!!) <$> randomRIO (0, length xs -1)
putStrLn . show $ item
This gives three different definitions for randomFood depending on what the input looks like.
Here I've also replaced putStrLn (show (item)) with putStrLn . show $ item - compose the functions show and putStrLn and apply ($) that to the item.
Few points to note :
Don't intermix pure and impure code.
Try to use library for a task rather than repeating what is already written.
Here is the code using random-fu library
import Data.Random
import Control.Applicative
food :: [String]
food = ["meatballs and potoes","veggisoup","lasagna","pasta bolognese","steak and fries","salad","roasted chicken"]
randomFood :: [String] -> RVar (Maybe String)
randomFood [] = return Nothing
randomFood xs = Just <$> randomElement xs
main :: IO ()
main = (sample $ randomFood food) >>= print
This is like choosing one element from a list randomly.
> main
Just "steak and fries"
> main
Just "meatballs and potoes"
If you want to output just a random permutation of the above list, you can use shuffle like
main = (sample $ shuffle food) >>= print
Example
> main
["meatballs and potoes","lasagna","steak and fries","roasted chicken","salad","pasta bolognese","veggisoup"]
> main
["roasted chicken","veggisoup","pasta bolognese","lasagna","steak and fries","meatballs and potoes","salad"]
I have a real problems with programm, which should be written with signature IO[(Int, Int)].
For me, as really beginner, it's quite hard to understand how it should look like.
So,this is task:
You should write a procedure with takes lines from user until empty line. After that it should return every line length. I try to make it more understandable with example
*Main> Take
kdfdfdf
dfdfeer
ererere
[(7,7),(7,0)]
Reading part it's quite understandable, unless, it's doesn't work actually as I want
Read
= do
putStrLn "User, your turn!"
line <- getLine
if line==""
then return ...
else do
line <-Read
return line {- actually doesn't return a line -}
I will be very glad, if someone make me understand how to write this
What exactly do you want Read to do? As is, it won't compile for a few reasons. You can't name a function or constant starting with a capital letter, those are reserved for Data constructors. Also, I'm sure you know, but the line return ... isn't valid syntax in Haskell.
I don't really understand why you want a list of pairs either if you just want to return the lengths of each line then something like this would work.
lineLengths :: IO [Int]
lineLengths = do
putStrLn "User, your turn!"
line <- getLine
if line == ""
then return []
else do
moreLines <- lineLengths
return $ (length line) : moreLines
This will prompt the user to enter a line, and if it is an empty line then it will return an empty list, assuming you don't care about the length of the empty line required to stop the interaction. Otherwise it will recurse and prepend the length of the line onto the list of lineLengths that was calculated.
EDIT:
If you really want a list of pairs, I think the best way is probably to use another function like this.
toPairs :: [Int] -> [(Int,Int)]
toPairs [] = []
toPairs [x] = [(x,0)]
toPairs (x:y:zs) = (x,y) : toPairs zs
Then to combine this with the reading function we can do this:
lineLengthPairs :: IO [(Int,Int)]
lineLengthPairs = do
ls <- lineLengths
return $ toPairs ls
So im educating myself for the future
firstLetter :: IO String
firstLetter = do
x <- getChar
if (x == ' ')
then return (show x)
else firstLetter
So it would get lines until the first line, that starts with empty char
how can I do it, so if empty line comes, it returns all head(x)
for example:
Liquid
Osone
Liquid
(empty line)
returns
"LOL"
Try this. The library function lines will split the input into lines for you, so all that is left is extracting the first character from each string in a list until one string is empty. An empty string is just a null list, so you can check for that to end the recursion over the list of strings.
firstLetters :: [String] -> String
firstLetters (x:xs)
| null x = []
| otherwise = head x : firstLetters xs
main = do
contents <- getContents
putStrLn . firstLetters . lines $ contents
Have you seen interact? This'll help you eliminate the IO and that always seems to make thing simpler for me and hopefully you too.
That reduces it to a problem that reads a string and returns a string.
Here's a rough go at it. getLines takes a string, breaks it into lines and consumes them (takeWhile) until it meets a line containing a single space (I wasn't sure on your ending condition, as the other poster says using null will stop at the first empty list). Then it goes over those lines and gets the first character of each (with map head).
getLines :: String -> String
getLines = map head . takeWhile (/= " ") . lines
main :: IO ()
main = interact getLines