New line in Haskell - haskell

I've been looking through previously asked questions and I can't find an answer that solves my problem, although I thought at least one of them would. I'm simply trying to have a newline character added between my strings inside of a function. Whenever I add a "\n" to a string, it simply prints the "\n"
import Data.List
-- aRow takes number of columns as argument
-- The idea is to use this function with the number of columns as argument.
-- Example, if we want 3 columns, we'd say aRow 3, and get "+---+---+---+"
aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++ take (4*n) (intercalate "" (repeat " |"))
This is the output I'm getting
"+---+---+---+---+\n| | | | |"
and I'd prefer
"+---+---+---+---+"
"| | | | |"
Where the lines are on separate lines (Also there's supposed to be 3 spaces between the vertical bars, ignore my formatting. I'm mainly trying to get the newline character working). Thank you.

https://stackoverflow.com/a/5944062/1848654:
If you just evaluate a string expression in ghci without using putStr or putStrLn, it will just call show on it, so for example the string "foo\n" will display as "foo\n" in ghci, but that does not change the fact that it's a string containing a newline and it will print that way, once you output it using putStr.
Long story short, you may want to use putStr as Haskell will default to using show on that string and that will display the \n plainly as it has done for you here.
Example:
import Data.List
main = putStrLn(aRow 4)
aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++ take (4*n) (intercalate "" (repeat " |"))

Related

Haskell writes '\n' instead of a newline

I have this code and instead of it printing out "\n", I want it to put the next string on a new line, but cannot seem to figure it out. Any pointers?
onSeparateLines :: [String] -> String
onSeparateLines [] = ""
onSeparateLines ( x:[] ) = x
onSeparateLines ( x:xs ) = x ++ "\n" ++ onSeparateLines xs
what I get is
"AAAA\nAAAA"
which should be:
"AAAA"
"AAAA"
The given function and your use of "\n" are correct, so the error must be elsewhere. Without knowing the details, I suspect that you are using (the equivalent of) print rather than putStr to print your string. Make sure that your string is not being shown before it is printed.
If this is in GHCi, be aware that values are printed using print, so
> onSeparateLines ["foo", "bar"]
will print the string and show escaped characters. You want
> putStrLn (onSeparateLines ["foo", "bar"])
instead.

Haskell new line not working

Been messing around for about 20 minutes now trying to get the new line working however it always shows in GHCI as a single line.
Here is what I enter into GHCi:
displayFilm ("Skyfall",["Daniel Craig", "Judi Dench", "Ralph Fiennes"], 2012, ["Bill", "Olga", "Zoe", "Paula", "Megan", "Sam", "Wally"])
Here is what is printed:
"Skyfall----------\n Cast: Daniel Craig, Judi Dench, Ralph Fiennes\n Year: 2012\n Fans: 7\n"
displayList :: [String] -> String
displayList [] = ""
displayList [x] = x ++ "" ++ displayList []
displayList (x:xs) = x ++ ", " ++ displayList xs
displayFilm :: Film -> String
displayFilm (title, cast, year, fans) =
title ++ "----------" ++
"\n Cast: " ++ (displayList cast) ++
"\n Year: " ++ (show year) ++
"\n Fans: " ++ show (length fans) ++ "\n"
To print a string as it is, without escaping special characters, use:
putStr string
or
putStrLn string
if you want an extra newline at the end. In you case, you are probably looking for
putStr (displayFilm (....))
Why is this needed? In GHCi, if you evaluate an expression s the result will be printed as if running print s (unless it has type IO something -- forget about this special case). If e is a string, print escapes all the special characters and output the result. This is because print is meant to output a string whose syntax follows the one in Haskell expressions. For numbers, this is the usual decimal notation. For strings, we get quotes and escaped characters.
When you type an expression into GHC, it displays it using print. Calling print on a string shows its content but does not evaluate escape sequences:
> print "line1\nline"
"line1\nline2"
Note the quotes.
To display the string as you desire, use putStr or putStrLn (the latter will append a newline).
> putStr "line1\nline2"
line1
line2

Printing a values in a tuple in a format

This question may seem silly but kindly bear with me
i was intending to print a tuple as
String1 - 10
Sritng2 - 20
String3 - 30
but if i am
putStrLn $ show(tuples)
It is giving me the out put as [("String",10),("String",20),("String",30)]
The Show instance is meant to convert the data to a string that can then be directly parsed back to the data type using a Read instance. If you want to do something like this, you need to write your own pretty printing function:
pprintTuple :: (Show a, Show b) => (a, b) -> String
pprintTuple (a, b) = show a ++ " - " ++ show b
With this function, you can convert each tuple to a string, then print those out one line at a time using putStrLn and mapM_:
mapM_ putStrLn $ map pprintTuple tuples
mapM_ is like map, but it works with monadic functions and also throws away any value returned. Since putStrLn doesn't return a value other than (), it's what you want to use here.
According to the output given by show and your expected output, looks like this is what you want:
putTuples ts = mapM_ putStrLn $ zipWith showTuple ts [1..]
where
showTuple (str, num) seq = str ++ show seq ++ " - " ++ show num
Testing:
> let ts = [("String",10),("String",20),("String",30)]
> putTuples ts
String1 - 10
String2 - 20
String3 - 30
There's also another way to print tuples which offers more control but requires an import of Text.Printf
Example:
> let xs = [("String1",10),("String2",20),("String3",30)]
> mapM_ (\(x, y) -> printf "%s - %d\n" x y) xs
String1 - 10
String2 - 20
String3 - 30
You could, of course, make lambda a named function.
I find it useful when there's a lot to print.

Haskell extract substring within a string

My goal is to find the number of times a substring exists within a string.
The substring I'm looking for will be of type "[n]", where n can be any variable.
My attempt involved splitting the string up using the words function,
then create a new list of strings if the 'head' of a string was '[' and
the 'last' of the same string was ']'
The problem I ran into was that I entered a String which when split using
the function words, created a String that looked like this "[2],"
Now, I still want this to count as an occurrence of the type "[n]"
An example would be I would want this String,
asdf[1]jkl[2]asdf[1]jkl
to return 3.
Here's the code I have:
-- String that will be tested on references function
txt :: String
txt = "[1] and [2] both feature characters who will do whatever it takes to " ++
"get to their goal, and in the end the thing they want the most ends " ++
"up destroying them. In case of [2], this is a whale..."
-- Function that will take a list of Strings and return a list that contains
-- any String of the type [n], where n is an variable
ref :: [String] -> [String]
ref [] = []
ref xs = [x | x <- xs, head x == '[', last x == ']']
-- Function takes a text with references in the format [n] and returns
-- the total number of references.
-- Example : ghci> references txt -- -> 3
references :: String -> Integer
references txt = len (ref (words txt))
If anyone can enlighten me on how to search for a substring within a string
or how to parse a string given a substring, that would be greatly appreciated.
I would just use a regular expression, and write it like this:
import Text.Regex.Posix
txt :: String
txt = "[1] and [2] both feature characters who will do whatever it takes to " ++
"get to their goal, and in the end the thing they want the most ends " ++
"up destroying them. In case of [2], this is a whale..."
-- references counts the number of references in the input string
references :: String -> Int
references str = str =~ "\\[[0-9]*\\]"
main = putStrLn $ show $ references txt -- outputs 3
regex is huge overkill for such a simple problem.
references = length . consume
consume [] = []
consume ('[':xs) = let (v,rest) = consume' xs in v:consume rest
consume (_ :xs) = consume xs
consume' [] = ([], [])
consume' (']':xs) = ([], xs)
consume' (x :xs) = let (v,rest) = consume' xs in (x:v, rest)
consume waits for a [ , then calls consume', which gathers everything until a ].
Here's a solution with
sepCap.
import Replace.Megaparsec
import Text.Megaparsec
import Text.Megaparsec.Char
import Data.Either
import Data.Maybe
txt = "[1] and [2] both feature characters who will do whatever it takes to " ++
"get to their goal, and in the end the thing they want the most ends " ++
"up destroying them. In case of [2], this is a whale..."
pattern = single '[' *> anySingle <* single ']' :: Parsec Void String Char
length $ rights $ fromJust $ parseMaybe (sepCap pattern) txt
3

Newline in Haskell String?

How can I create a newline inside a String? Is it possible without using IO ()?
formatRow :: Car -> String
formatRow (a, d:ds, c, x:xs) = a ++ " | " ++ x ++ concat xs ++ " | " ++ show c ++ " | " ++ d ++ concat ds ++ (show '\n')
To create a string containing a newline, just write "\n".
If you run your program on Windows, it will automatically be converted to "\r\n".
Note that calling show on it will escape the newline (or any other meta-characters), so don't do foo ++ (show "\n") or foo ++ (show '\n') - just use foo ++ "\n".
Also note that if you just evaluate a string expression in GHCi without using putStr or putStrLn, it will just call show on it, so for example the string "foo\n" will display as "foo\n" in GHCi, but that does not change the fact that it's a string containing a newline and it will print that way, once you output it using putStr.

Resources