Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I functionally concatenate a number and string?

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.

like image 862
Maxpm Avatar asked Feb 04 '12 21:02

Maxpm


People also ask

Can you concatenate a string and a number?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do I concatenate a number and a string in Excel?

To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator.

What method is used to combine strings and number?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.


1 Answers

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;
}
like image 136
fnl Avatar answered Sep 17 '22 18:09

fnl