Char value in F#

f#
10,212

Solution 1

If the 'mapping' is more arbitrary, you could use a strategy like the code below, where you can specify a data structure of what value each letter maps to.

#light

let table = [
    'C', 3
    'O', 15
    'L', 12
    'I', 9
    'N', 14
    ]

let dictionary = dict table

let Value c = 
    match dictionary.TryGetValue(c) with
    | true, v -> v
    | _ -> failwith (sprintf "letter '%c' was not in lookup table" c)

let CalcValue name =
    name |> Seq.sum_by Value

printfn "COLIN = %d" (CalcValue "COLIN")

Solution 2

What you have is decent; here's another version:

#light

let Value (c:char) = 
    (int c) - (int 'A') + 1

let CalcValue name =
    name |> Seq.sum_by Value

printfn "COLIN = %d" (CalcValue "COLIN")
// may be of interest:
printfn "%A" ("COLIN" |> Seq.map Value |> Seq.to_list)

It assumes the original input is uppercase. "int" is a function that converts a char (or whatever) to an int; Seq.sum_by is perfect for this.

I also show an example of using map, not sure what you're interested in.

Solution 3

I've found a hackish way to do this using the ascii value of the character, and getting the number from there but i think there might be a better way.

let tcalculate name =
    name.ToString().ToLower().ToCharArray()
    |> Seq.map (fun char -> Convert.ToInt32 char - 96)
    |> Seq.sum 

work's beautifully and maybe even more efficient then "mapping" but I'd like to view the solution I asked for

thanks all.

Solution 4

all you need to do, is make the string lowercase, turn it into a char array like you have done, loop through each letter, take the value of each char and subtract the value of 'a' and add one. that will make each letter have the value of its position in the alphabet.

Share:
10,212
SKG
Author by

SKG

Updated on June 04, 2022

Comments

  • SKG
    SKG almost 2 years

    Lets say I have a string "COLIN".

    The numeric value of this string would is worth:

    3 + 15 + 12 + 9 + 14 = 53.

    So

    A = 1, B = 2, C = 3, and so on.

    I have no idea how to even start in F# for this.

    let mutable nametotal = 0
    let rec tcalculate name =
        name.ToString().ToCharArray()
        |> Seq.length
    

    Here is what I have so far. The seq.length is just there for testing to see if the toCharArray actually worked.