On Thursday, 27 October 2022 at 01:57:15 UTC, Salih Dincer wrote:

You should help the compiler with return type:

I love D, enjoys it when I code...:)

I played a little on the code, and the following is possible and beautiful:

```d
// If you type auto instead of ubyte as return type, the return will be char.
ubyte toHexDigit(bool capital = false)(ubyte decimal)
{
  static if(capital) enum start = 'A';
                else enum start = 'a';
  if(decimal < 10)
    return cast(char)(decimal + ubyte('0'));

  if(decimal < 16)
    return cast(char)(decimal - ubyte(10)
                              + ubyte(start));
  return '\xFF';
}

unittest
{
  assert(is(typeof(toHexDigit(9)) == ubyte));

  assert(toHexDigit(9) == 57); // '9'
  assert(toHexDigit(10) == 97); // 'a'
  assert(toHexDigit!true(10) == 65); // 'A'
}
```
SDB@79

Reply via email to