Using "printf" on a list in Haskell - haskell

How can i use printf over a list?
I have a list of numbers and i want to print them all by respecting a format (ex: %.3f). I tried to use map over printf, but it does not work. So, i have no idea. Can somebody help me with this? Any ideas are acceptable. Is there a way to create a string from a list respecting a custom format?

printf can produce strings instead of just printing them to stdout. This
is because it is overloaded on its result type (it's also part of machinery
that makes it variadic).
import Text.Printf
main :: IO ()
main = putStrLn . unwords $ printf "%.3f" <$> ([1..10] :: [Double])
That should do the trick.
BTW, printf is not type safe and can blow at run time. I recommend you use
something like
formatting.

Related

Words returns wrong output when a String has apostrophes in it

I am trying to split a String into a list of words
split_string :: String -> [Word]
split_string x = words x
"Functional Programming is Fun, isn’t it?" should give me back:
["Functional","Programming","is","Fun,","isn’t","it?"]
but it returns me this instead:
["Functional","Programming","is","Fun,","isn\8217t","it?"]
How can I avoid problem with the apostrophes problem?
I am new to Haskell so sorry in advance if this is a stupid question.
There is a common misunderstanding about what Haskell's Show mechanism is there for. Many beginners think it is supposed to yield pretty visualisations, but actually its purpose is specifically to generate representations that are valid Haskell code.
That means in particular that they shouldn't contain stuff that would cause an error if you copy&paste it back into a Haskell file.For example, consider the string you tried to show "something" on the terminal. If GHCi displayed this as
"you tried to show "something" on the terminal"
that would incur a parse error. The quotation marks need to be escaped:
"you tried to show \"something\" on the terminal"
and that's the form that the Show String instance generates.
Generally, the representation is not unique. For example
"you tried to show \34something\34 on the terminal"
would also work, where \34 is the ASCII character code for the " symbol. This form can in fact be used for any characters:
Prelude> "\72\101\108\108\111\44\32\87\111\114\108\100"
"Hello, World"
Of course it's silly to do that for all characters, but the Haskell standard plays it safe in the sense that all non-ASCII characters are displayed in the escaped way:
Prelude> "Amila Bečirović"
"Amila Be\269irovi\263"
The advantage is that you're safe from quirks that could be introduced by incompatible character encodings – in the early 2000s this would often happen when Webpages used language-specific 8-bit encodings. By now this shouldn't really be an issue anymore.
As Willem Van Onsem wrote, you can always just raw-dump a string with putStrLn, which doesn't escape anything – though this isn't directly applicable to a list of strings.
For more flexibility, you can opt for a different Show class that doesn't have this behaviour, such as from the pragmatic-show package:
Prelude> import qualified Text.Show.Pragmatic as SP
Prelude SP> SP.print ["Functional","Programming","is","Fun,","isn’t","it?"]
["Functional","Programming","is","Fun,","isn’t","it?"]
Prelude SP> SP.print "Amila Bečirović"
"Amila Bečirović"
Note that this will still escape characters that really are unsafe:
Prelude SP> SP.print "bla\34blub"
"bla\"blub"
This is not the string content. This is the representation of a string. If you write "foo" for a string literal, then the double quotes are not part of the content of the string. These are used to write a string literal.
Normally the Show typeclass will return for the show of an objects a string where the content of the string looks like a Haskell expression. This makes it more convenient to later copy paste the value in the code.
You can print the content of a string with putStrLn :: String -> IO (). For example:
Prelude> putStrLn "isn’t"
isn’t
Prelude> putStrLn "isn\8217t"
isn’t

How to call multiple functions within the code in haskell

I would like to call multiple functions from within the code, meaning that by executing the .hs file, all functions named will be executed.
I tried using main with putStrLn, but this is rather complicated and doesn't seem to work.
main = do
putStrLn (myFunction para1 para2)
putStrLn (anotherFunction para1 para2)
This shows the idea, but it obviosly doesn't work. Escpecially because myFunction returns an Integer and not a char.
I hope someone can help. Thank you in advance.
using "print" solved this problem. Thank you.
Escpecially because myFunction returns an Integer and not a char.
You can use print to print things other than strings. print is equivalent to putStrLn . show, so it can print any type that's showable, which Integer is.

Convert one full String to ints and words as an interpreter in Haskell

I am trying to write a Forth interpreter in Haskell. There are many sub problems and categories to accomplish this, however, I am trying to accomplish the most basic of steps, and I have been at it for some time in different approaches. The simple input case I am trying to get to is "25 12 +" -> [37]. I am not worried about the lists in Forth are backwards from Haskell, but I do want to try and accommodate the extensibility of the input string down the road, so I am using Maybe, as if there is an error, I will just do Nothing.
I first tried to break the input string into a list of "words" using Prelude's words function. From there I used Prelude's reads function to turn it into a list of tuples (Int,String). So this works great, up until I get to a command "word", such as the char + in the sample problem.
So how do I parse/interpret the string's command to something I can use?
Do I create a new data structure that has all the Forth commands or special characters? (assuming this, how do I convert it from the string format to that data type?)
Need anything else, just ask. I appreciate the help thinking this through.
read is essentially a very simple string parser. Rather than adapting it, you might want to consider learning to use a parser combinator library such as Parsec.
There are a bunch of different tutorials about parser combinators so you'll probably need to do a bit of reading before they 'click.' However, the first example in this tutorial is quite closely related to your problem.
import Text.Parsec
import Text.Parsec.String
play :: String -> Either ParseError Integer
play s = parse pmain "parameter" s
pmain :: Parser Integer
pmain = do
x <- pnum `chainl1` pplus
eof
return x
pnum = read `fmap` many1 digit
pplus = char '+' >> return (+)
It's a simple parser that evaluates arbitrarily long lists:
*Main> play "1+2+3+4+5"
Right 15
It also produces useful parse errors:
*Main> play "1+2+3+4+5~"
Left "parameter" (line 1, column 10):
unexpected '~'
expecting digit, "+" or end of input
If you can understand this simple parser, you should be able to work out how to adapt it to your particular problem (referring to the list of generic combinators in the documentation for Text.Parsec.Combinator). It will take a little longer at first than using read, but using a proper parsing library will make it much easier to achieve the ultimate goal of parsing Forth's whole grammar.

How to get the literal value of a TemplateHaskell named variable

If I have a Name in TemplateHaskell and want to find out the value of the variable that it names, provided that the variable is declared as a literal, can this be done?
var = "foo"
-- Can `contentsOf` be defined?
$((contentsOf . mkName $ "var") >>= guard . (== "foo"))
In theory, yes. In practice, no.
Finding out stuff about existing names is done using reify :: Name -> Q Info, and for a definition like that you would get back a VarI value, which includes a Maybe Dec field. This would seem to suggest that you might in some cases be able to get the syntax tree for the declaration of the variable, which would allow you to extract the literal, however current versions of GHC always returns Nothing in this field, so you're out of luck for a pure TH solution.
However, TH does allow arbitrary IO actions to be run, so you could potentially work around this by loading and parsing the module yourself using something like haskell-src-exts, however I suspect that would be more trouble than it's worth.

Haskell: Conditionally execute external process with Maybe FilePath

I am struggling to understand a block of code which is extremely easy in imperative world.
That's what I need to do: given an executable full path, which is a Maybe FilePath type, I need to execute it conditionally.
If the path is a Nothing - print an error, if the path is Just Path - execute it and print message that the file has been executed. Only "Hello, World" can be easier,right?
But in Haskell I dug my self into numerous layers of Maybe's and IO's and got stuck.
Two concrete questions arise from here:
How do I feed a Maybe FilePath into a system or rawSystem? liftM does not work for me here.
What is the correct way of doing this kind of conditional branching?
Thanks.
Simple pattern matching will do the job nicely.
case command of
Just path -> system path >> putStrLn "Done"
Nothing -> putStrLn "None specified"
Or, if you'd rather not pattern-match, use the maybe function:
maybe (putStrLn "None specified") ((>> putStrLn "Done") . system) command
That may occasionally be nicer than matching with a case, but not here, I think. The composition with the printing of the success message is clunky. It fares better if you don't print messages but return the ExitCode in both branches:
maybe (return $ ExitFailure 1) system command
This is exactly what the Traversable type class was made for!
Prelude Data.Traversable System.Cmd> traverse system Nothing
Nothing
Prelude Data.Traversable System.Cmd> traverse system (Just "echo OMG BEES")
OMG BEES
Just ExitSuccess

Resources