1

I have heard that the usage of show and read is a bottleneck in the program. Is there a function like this which doesn't involve string transformation:

thow :: Num a => a -> Text
thow = undefined

One obvious implementation is like this pack . show but unfortunately that involves string conversion. Is there any optimal way for achieving this ?

Community
  • 1
  • 1
Sibi
  • 47,472
  • 16
  • 95
  • 163
  • In this general form: No. But for a concrete type (say, `Integer -> Text`), maybe. Which is it you need? – Joachim Breitner Aug 02 '14 at 20:49
  • 1
    Neither `Num a => a -> Text` nor `Num a => a -> String` can be implemented. Why would you want to do this, by the way? How would you use `thow`? –  Aug 02 '14 at 20:50
  • 1
    Rhymoid: That’s not right. `Show` is a superclass of `Num`, so `show :: Num a => a -> String`. Or at least it used to be the case... – Joachim Breitner Aug 02 '14 at 20:51
  • @JoachimBreitner I would be happy even with a concrete type. Is it achievable for `Integer -> Text` ? – Sibi Aug 02 '14 at 20:52
  • 2
    @JoachimBreitner: wait, hasn't `Show` been removed as a superclass of `Num`? –  Aug 02 '14 at 20:52
  • Guess hayoo is still on an older version. So we are both right :-) – Joachim Breitner Aug 02 '14 at 20:56
  • @Rhymoid Interesting. Was there any reason for removing `Show` ? – Sibi Aug 02 '14 at 21:03
  • 2
    @Sibi: There's no good reason to depend on `Eq` or `Show`. `Eq` is involved in literal patterns, but I don't think that's such a useful feature to bake into `Num`. The functionality in `Show` is completely disjoint from `Num`'s. The real problem is that you can't create more abstract instances, like `instance Num a => Num (z -> a)`, because functions can neither be shown nor compared. –  Aug 02 '14 at 21:09

2 Answers2

8

Looking through the docs of the text package, you probably want to use the functions in Data.Text.Lazy.Builder.Int, e.g.:

thow :: Integral a => a -> Text
thow = toLazyText . decimal

If you look at the code of that module you see that it has RULES and SPECIALIZE pragmas in place to optimize this, if a is one of the common integral types.

Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139
3

The double-conversion package does this for Float and Double, and is highly optimized. I doubt you'd be able to match its performance with a polymorphic function (although you could always specialize with a RULE).

John L
  • 27,937
  • 4
  • 73
  • 88
  • Note that `Data.Text.Lazy.Build.Int` also has that; I extended my answer. – Joachim Breitner Aug 03 '14 at 07:43
  • By "that", I presume you mean RULES and not conversions for `Float` and `Double` (those are available in `Data.Text.Lazy.Builder.RealFloat`. Those certainly work, although IIRC they're less efficient than `double-conversion`. Better than `show` though. – John L Aug 03 '14 at 21:08