PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] Why is this Haskell program making backslashes?

 August 18, 2022     haskell, output, recursion, string     No comments   

Issue

I'm new to Haskell, and wrote this program to practice functional programming. I have no idea if it is a good program, except for two things.

  • It works (it shows me the path from 6 to 1 in a Collatz tree)
  • It prints way too many backslashes
next_step :: Integer -> Integer
collatz :: Integer -> String

next_step n = do
        if (n `mod` 2) == 0 then
                n `div` 2
        else
                (n * 3) + 1

collatz 1 = "1"
collatz n = (show n) ++ " -> " ++ (show (collatz (next_step n)))

main = putStrLn (collatz 6)

Output:

6 -> "3 -> \"10 -> \\\"5 -> \\\\\\\"16 -> \\\\\\\\\\\\\\\"8 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"4 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"2 -> \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\"\""

I would like for the backslashes to go away.


Solution

collatz already returns a string, so you don't need to call show on it:

collatz n = show(n) ++ " -> " ++ collatz (next_step n)

Using show adds quotes, which then causes the backslashes due to nested quotes.



Answered By - happydave
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing