Hacker News new | ask | show | jobs
by 0xcoffee 2472 days ago
Obligatory C#:

    var input = new string[] { "abc", "ab", "abcdef", "abcdefgh" };
    var maxLength = input.Select(e => e.Length).Max();
    var output = input.Select(e =>
    {
        var padding = (maxLength - e.Length) / 2;
        return new String(' ', padding) + e;
    });
Most modern `oop` languages these days all support functional constructs and achieve the same thing in same amount of code & style. Language and oop/functional style are not mutually exclusive anymore, which this article seems to overlook by comparing both languages and styles at the same time.
3 comments

This looks like the Java if the Java was written by someone who knows Java:

    List<String> alignText(List<String> texts) {
      int maxLength = texts.stream().mapToInt(String::length).max().orElse(0);
      return texts.stream().map(text -> {
        var spaceCount = (maxLength - text.length()) / 2;
        return " ".repeat(spaceCount) + text;
      }).collect(Collectors.toList());
    }
/nit Move the lambda to private method and replace it with method reference and it’ll be just perfect
Good feedback. +1
I tend to avoid doing a Select followed straight by a Max when you can just pass the select function directly into the max. Also multiline lambda expressions feel ugly but that's probably just me! This is what I would do these days:

    string pad(this string e, int padLength) => new String(' ', padLength) + e;
    var input = new string[] { "abc", "ab", "abcdef", "abcdefgh" };
    var maxLength = input.Max(e => e.Length);
    var output = input.Select(e => e.pad((maxLength - e.Length) / 2));
Sadly C# is still missing a few important ML features that making functional programming more difficult than in a true ML.
It would be interesting if you could mention which feature/s you think it most sorely lacks. Some of the recent syntax additions have made it really easy to write concise functional code. I don't even use curly braces much anymore. What about f#?