haskell,formatting,rational , How to convert a Rational into a “pretty” String?

## Question:

I want to display some `Rational` values in their decimal expansion. That is, instead of displaying `3 % 4`, I would rather display `0.75`. I'd like this function to be of type `Int -> Rational -> String`. The first `Int` is to specify the maximum number of decimal places, since `Rational` expansions may be non-terminating.

Hoogle and the haddocks for Data.Ratio didn't help me. Where can I find this function?

Here's one that I wrote a few weeks ago. You can specify the number of decimals you want (correctly rounded), or just pass `Nothing` in which case it will print the full precision, including marking the repeated decimals.

``````module ShowRational where
import Data.List(findIndex, splitAt)

-- | Convert a 'Rational' to a 'String' using the given number of decimals.
-- If the number of decimals is not given the full precision is showed using (DDD) for repeating digits.
-- E.g., 13.7/3 is shown as \"4.5(6)\".
showRational :: Maybe Int -> Rational -> String
showRational (Just n) r =
let d = round (abs r * 10^n)
s = show (d :: Integer)
s' = replicate (n - length s + 1) '0' ++ s
(h, f) = splitAt (length s' - n) s'
in  (if r < 0 then "-" else "") ++ h ++ "." ++ f
-- The length of the repeating digits is related to the totient function of the denominator.
-- This means that the complexity of computing them is at least as bad as factoring, i.e., it quickly becomes infeasible.
showRational Nothing r =
let (i, f) = properFraction (abs r) :: (Integer, Rational)
si = if r < 0 then "-" ++ show i else show i
decimals f = loop f [] ""
loop x fs ds =
if x == 0 then
ds
else
case findIndex (x ==) fs of
Just i  -> let (l, r) = splitAt i ds in l ++ "(" ++ r ++ ")"
Nothing -> let (c, f) = properFraction (10 * x) :: (Integer, Rational) in loop f (fs ++ [x]) (ds ++ show c)
in  if f == 0 then si else si ++ "." ++ decimals f
``````

# Related:

## What does this horribly ugly (yet somehow secretly beautiful) Perl code do?

perl,formatting,deobfuscation
I found this code in a Powerpoint presentation about Perl scripting and this was on a page demonstrating how ugly Perl code can get if you really wanted to make it that way. The presentation says nothing about what this code does. Honestly I am just very curious to know......

## Get each fibbonacci value in haskell

I'm learning haskell and I have the following code: fib a b = a : fib b (a + b) findFibSum = sum [x | x <- fib 1 2, mod x 2 == 0 && x < 100] If I run findFibSum nothing happens, it just sits there. Shouldn't...

## Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

## IO Monad Example

Consider the following IO code: ghci> let x = return 100 :: IO Int ghci> :t do { a <- x; print a; return 500 } do { a <- x; print a; return 500 } :: Num b => IO b My understanding of do notation/bind is that the...

## Formatting large numbers in C#

c#,.net,unity3d,formatting
I am using Unity to make an "Incremental Game" also known as an "Idle Game" and I am trying to format large numbers. For example, when gold gets to say 1000 or more, it will display as Gold: 1k instead of Gold: 1000. using UnityEngine; using System.Collections; public class Click...

## Recursion scheme in Haskell for repeatedly breaking datatypes into “head” and “tail” and yielding a structure of results

In Haskell, I recently found the following function useful: listCase :: (a -> [a] -> b) -> [a] -> [b] listCase f [] = [] listCase f (x:xs) = f x xs : listCase f xs I used it to generate sliding windows of size 3 from a list, like...

## How to dynamically set currency symbol in Excel custom format?

excel,formatting,format
The figures in my spreadsheet use the following custom formatting: €#,###.##,, "M" So figures are expressed in millions with 2 decimal places prefixed by the euro symbol and followed by M for millions. My workbook will need to be converted to other currencies and I don't want to have to...

## Haskell: When declaring a class, how can I use a type variable that is not immediately in the constructors?

I want to define a function, <-? to check whether an element is in a list/set/map. module Test where import qualified Data.Map as Map import qualified Data.Set as Set class Memberable a where (<-?) :: b -> a -> Bool instance Memberable [x] where (<-?) = elem instance Memberable (Map.Map...

## How to set font-weight of a column text to bold based on another column value in Telerik Grid

telerik,formatting,conditional,client-templates
I have a Telerik grid in which based on whether my IsTrue value is true or false, I need to set the font-weight of Name text in only that particular row to bold. I tried the following but I seem to be missing something. columns.Bound(d => d.IsTrue).Width(0).HtmlAttributes(new { id="hdnIsTrue", style...

## Display a table in MATLAB

matlab,formatting
I am trying to display a table with two columns and 86 rows. Instead of outputting the rows, the size is stated. Is there a way to change this? I am new to MATLAB and am coming from a background in C/C++ so I may just be approaching this all...

## apply a transformation with function inline

Starting from a simple case of "fold" (I used (+) but can be anything else): Prelude.foldl (+) 0 [10,20,30] is it possible apply an inline transformation similar to (that doesn't work): Prelude.foldl ((+) . (\x -> read x :: Int)) 0 ["10","20","30"] In case not, is there an alternative to...

## How to serialize a custom formatted time to/from xml in Go?

xml,go,formatting,date-formatting
When serializing a datetime to/from xml how do I make it use a custom time format?

## Haskell do clause with multiple monad types

I'm using a graphic library in Haskell called ThreePennyUI. In this library the main function returns a UI monad object. This causes me much headache as when I attempt to unpack IO values into local variables I receive errors complaining of different monad types. Here's an example of my problem:...

## Python 2.7 Etree/lxml minimizing [duplicate]

python,xsd,formatting,lxml
This question already has an answer here: Close a tag with no text in lxml 3 answers Im using lxml/Etree to parse and write to XSD documents. I have the basic structure tree = ET.parse('file.xsd') # do stuff tree.write('output.xsd') But tags get minimized in some instances, for example: <Cars>...

## Combining Event and an attribute in threepenny-gui

I have an Event String which I want to sink into a textarea. This works fine, but now I want to combine the current value of a checkbox selection to this string. First I did this by using checkedChange of the checkbox which works, but has a problem. If the...

## Best practice for handling data types from 3rd party libraries in Haskell?

I'm just getting into my first real Haskell project of size (a web app), and I'm starting to run into issues with types from 3rd party libraries leaking all over my code. Here is a quick example: My Parser module imports Test.Parsec, and the exports a function (parseConfig) that returns...

## Refactor an IO recursive loop into a monad folding in Haskell

I writing a tcp server, and here's my main loop method: serverLoop :: Socket -> IO () serverLoop sock = do (conn, _) <- accept sock forkIO \$ handleConn conn serverLoop sock (Note: handleConn :: Socket -> IO () is a function specific to my program.) I would like to...

## Why doesn't `iterate` from the Prelude tie the knot?

Why isn't iterate defined like iterate :: (a -> a) -> a -> [a] iterate f x = xs where xs = x : map f xs in the Prelude?...

## Implementing map on a tree using fold

I am trying to implement a map using fold. I could do so in Haskell data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) foldTree :: Tree a -> b -> (b -> a -> b -> b) -> b foldTree EmptyTree d _ =...

## Retaining original table formatting after a 'pagebreak'

excel,excel-vba,table,formatting,page-break
So here's the finished product, a statement of accounts with a working statement table, and an ageing analysis: Everything works great. It basically populates itself row by row with data from another table. Here is the sample code: j = 21 'First row on the statement of accounts workbook For...

## Need help in writing this multiplication code

c,formatting,output,multiplication,spaces
I need to show process of multiplication in output.for ex:- inputs are two numbers(say 325 and 4405) the output would be:- 325 *4405 ----- 1625 0 1300 1300 ------- 1431625 NOTE:-number of spaces should be minimum. I don't need the exact code. Just tell me which property or way I...

## Formatting long-form survey data in R

r,table,formatting,reshape,long-form
We asked 3 people two or three yes-no questions. Let me denote these 3 people by 101,102,103 the questions by "A", "B","C" and the responses by 0, 1. The result is q<-data.frame(response=c(0,0,1,0,0,1,1), qstn=c("A","B","A","B","A","B","C"), person=c(101,101,102,102,103,103,103)) We need to convert this table to the following format person|qustionA|questionB|questionC 101 | 0 | 0...

## First three items of a list in Haskell

I am very new to Haskell, and struggling a bit with a function here. The premise is simple enough: Run through a list, and combine each 3 items next to each other with another function and return a list with the results. The problem is to do it in a...

## Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

## logical expression evaluator Haskell

I wrote the following logical expression evaluator. It works for simple 2-member expressions, and it runs but produces a fault for expression containing other expressions as the second/first member. Here's my code. data Expression = Literal Bool | Operation Operator Expression Expression data Operator = AND | OR eval ::...

## Replace all [ ] with {} - as short as possible [on hold]

Given the code below: import Data.List; main = (readLn :: IO [Integer]) >>= print . subsequences It takes a list of integers from standard input (for example [1,2,3]) and outputs something like: [[],,,[1,2],,[1,3],[2,3],[1,2,3]] I want it to be like this: {},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}} so my goal is to replace every [ and...

## How to “wrap” monadic return value

I have the following code: data APNSIdentifier = NoIdentifier | Identifier Word32 deriving (Show, Eq) newtype APNSItem = Item Put createNotificationIdentifierItem :: APNSIdentifier -> APNSItem <--- here createNotificationIdentifierItem (Identifier identifier) = do putWord8 3 putWord16be 4 putWord32be identifier How can I "wrap" the Put monad with an APNSItem? Do I...

## Hook into GHC runtime system

I have been looking at how transactional memory is implemented in Haskell, and I am not sure I understand how the STM operations exposed to the programmer hook into the runtime system functions written in C. In ghc/libraries/base/GHC/Conc/Sync.hs of the git repo, I see the following definitions: -- |A monad...

## Setting id and class with the haskell diagrams package

I am working with the diagrams package for haskell, and I am using the SVG backend. I embed the SVG markup directly into an HTML document, so that the graph as a part of a web page. I have built a pretty cool looking bar graph, and I would like...

## Thread blocked indefinitely in an MVar operation

I have been attempting to debug a problem when using multiple MVars, however to no luck. My code uses two MVars: one to store the servers current state, and another to pass network events to and from the client threads. However after connecting and disconnecting several times, the server stops...

## Haskell make recipe fails for Paradox theorem prover using GHC

I am trying to install the paradox theorem prover sourced from here. When I run the makefile this is the command that runs: ghc -optl -static -lstdc++ -I../instantiate -I../minisat/current-base ../minisat/current-base/Solver.or ../minisat/current-base/Prop.or ../instantiate/MiniSatWrapper.or ../instantiate/MiniSatInstantiateClause.or -fglasgow-exts -O2 -static -threaded -main-is Paradox.Main.main --make Paradox.Main -o paradox And it results in several errors like...

## issues with installing newer cabal version for haskell vim now

I would like to install this vim plugin: https://github.com/begriffs/haskell-vim-now When trying to run the suggested installation script: curl -o - https://raw.githubusercontent.com/begriffs/haskell-vim-now/master/install.sh | bash I get: --- Cabal version 1.18 or later is required. Aborting. I then try to install a newer version of cabal: [email protected]:~/Downloads/cabal-install-1.22.6.0\$ ./bootstrap.sh The response I get:...

## SSRS Average Time in Minutes and then Format to HH MM

sql,stored-procedures,reporting-services,formatting
I've seen a lot of questions about average time in SSRS but I'm pretty new to this and none of these questions address my specific need so any help would be appreciated. I have a duration field (Fields!Duration1.Value) which is pulling in a duration in minutes (example: 170). In my...

## Haskell - generate and use the same random list

In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it. How can I overcome this problem?...

## Keep track of loop without a counter

Say, I got a list which length can be odd or even. Every iteration , I remove two items from the list. If there is one or no item at the end, I end the execution. If I store (length list)/2 every loop, I will get e.g. [5,4,3...] for a...

## How does Frege generalize number literals?

It appears that Frege can evaluate 1/2 to return the Double value 0.5. The literal 1 is of type Int. It seems to be promoted to Double, which is a type in the Real class and thus knows the / operator. How does this happen? Is it using the Haskell...

## Haskell return lazy string from file IO

Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

## Fold over a heterogeneous, compile time, list

I have a list of heterogeneous types (or at least that's what I have in mind): data Nul data Bits b otherBits where BitsLst :: b -> otherBits -> Bits b otherBits NoMoreBits :: Bits b Nul Now, given an input type b, I want to go through all the...

## Altering XML file format in C#

c#,xml,formatting
I have a program in Visual Studio which gives the output in an XML file. It looks like so: <?xml version="1.0" encoding="utf-8"?> <leaCEDS> <district> <leaID>01</leaID> <name>Alachua</name> <organizationType>LEA</organizationType> <streetLine1>620 E University Ave</streetLine1> <city>Gainesville</city> <stateProvince>FL</stateProvince> <postalCode>326015448</postalCode> <county>Alachua</county>...

## Tokenizer identifier in Haskell

I'm writing this small program basically to identify each input tokens as operator/parenthesis/int. However, I encountered a problem stating that Not in scope: data constructor `Integer' Here's what I have so far (Data.Char only defines isDigit, nothing else) import Data.Char (isDigit) data Token = TPlus | TTimes | TParenLeft |...

## Idiomatic list construction

I'm very new to Haskell and functional programming in general, so I don't really know how to make this code idiomatic: type Coord = Double data Point = Point Coord Coord Coord deriving Show type Polyline = [Point] -- Add a point to a polyline addPoint :: Polyline -> Point...

## Haskell IO - read from standard input directly to list

Haskell IO system is super hard to understand for me so i have question : How to read from standard input to list ? I know that there is function getLine :: IO String and interact. But i do not know how to convert the input to list so I...

## When will travis-ci support ghc 7.10?

I'd like to use travis-ci on my Haskell projects, but they require the latest version of GHC.

## How can I express foldr in terms of foldMap for type-aligned sequences?

I'm playing around with type-aligned sequences, and in particular I'm messing around with the idea of folding them. A foldable type-aligned sequence looks something like this: class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b...

## How do I avoid writing this type of Haskell boilerplate code

I run into this situation often enough for it to be annoying. Let's say I have a sum type which can hold an instance of x or a bunch of other things unrelated to x - data Foo x = X x | Y Int | Z String | ...(other...

## Why is f <\$> g <\$> x equivalent to (f . g) <\$> x although <\$> is not right-associative?

Why is f <\$> g <\$> x equivalent to (f . g) <\$> x although <\$> is not right-associative? (This kind of equivalence is valid in a popular idiom with plain \$, but currently \$ is right-associative!) <*> has the same associativity and precedence as <\$>, but behaves differently! Example:...

## How to .write() two items, a zero and an iterator in Python?

python,csv,formatting,conditional-statements,writing
I may have a simple formatting question here - I would like to do something like hrOut.write('0',i) in order to add/preface a zero to 'i' which is a timestamp, but I don't know the correct syntax. My code is below. Thank you all. hrIn = open('HrsInput.csv') hrOut = open('HrsOutput.csv', 'wt')...