Can I functionally concatenate a number and string?
Asked Answered
O

1

6

I am trying to make a pure function that embeds a number in a string. The obvious concatenation methods do not work:

pure string foo(immutable int bar)
{
    return "Number: " ~ bar; // Error: strings and ints are incompatible.
    return "Number: " ~ to!string(bar); // Error: to() is impure.
}

Is there a clean, functional way to concatenate a number and string? I would like to avoid writing my own concatenation or conversion function, but I will if I have to.

Olli answered 4/2, 2012 at 21:39 Comment(0)
C
4

This seems to be a long-standing problem with to!. (See this bugreport.)

As far as I can tell, there are no matching pure functions in Phobos. I am afraid you are on your own.


Edit from the OP: I used a function like this one to convert uints to strings.

import std.math: log10;

pure string convert(uint number)
{
    string result;
    while (log10(number) + 1 >= 1)
    {
        immutable uint lastDigit = number % 10;
        result = cast(char)('0' + lastDigit) ~ result;
        number /= 10;
    }
    return result;
}
Chenille answered 4/2, 2012 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.