Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization of F# string manipulation

Tags:

string

f#

I am just learning F# and have been converting a library of C# extension methods to F#. I am currently working on implementing a function called ConvertFirstLetterToUppercase based on the C# implementation below:

public static string ConvertFirstLetterToUppercase(this string value) {
    if (string.IsNullOrEmpty(value)) return value;
    if (value.Length == 1) return value.ToUpper();
    return value.Substring(0, 1).ToUpper() + value.Substring(1);
}

The F# implementation

[<System.Runtime.CompilerServices.ExtensionAttribute>]
module public StringHelper
    open System
    open System.Collections.Generic
    open System.Linq

    let ConvertHelper (x : char[]) =  
        match x with
            | [| |] | null -> ""
            | [| head; |] -> Char.ToUpper(head).ToString()
            | [| head; _ |] -> Char.ToUpper(head).ToString() + string(x.Skip(1).ToArray())

    [<System.Runtime.CompilerServices.ExtensionAttribute>]
    let ConvertFirstLetterToUppercase (_this : string) =
        match _this with
        | "" | null -> _this
        | _ -> ConvertHelper (_this.ToCharArray())

Can someone show me a more concise implementation utilizing more natural F# syntax?

like image 505
Norman H Avatar asked Aug 03 '10 17:08

Norman H


People also ask

What is an optimization formula?

Optimization equation: A = x y A = x y = x (L - 2 x)/2 = - x2 + (L/2) x = f (x) f '(x) = - 2 x + (L/2) To optimize f(x), we set f '(x) = 0.

What is optimization method?

Optimization methods are used in many areas of study to find solutions that maximize or minimize some study parameters, such as minimize costs in the production of a good or service, maximize profits, minimize raw material in the development of a good, or maximize production.


1 Answers

open System

type System.String with
    member this.ConvertFirstLetterToUpperCase() =
        match this with
        | null -> null
        | "" -> ""
        | s -> s.[0..0].ToUpper() + s.[1..]

Usage:

> "juliet".ConvertFirstLetterToUpperCase();;
val it : string = "Juliet"
like image 165
Juliet Avatar answered Sep 28 '22 00:09

Juliet