2009-02-09 62 views
1

可以说我有一个字符串“COLIN”。F中的Char值#

此字符串的数值将是值得:

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

所以

A = 1,B = 2,C = 3等等。

我不知道该如何在F#中启动。

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

这是我到目前为止。 seq.length就在那里进行测试,看看toCharArray是否真的有效。

回答

3

如果“映射”是更加随心所欲,你可以使用如下代码的策略,在那里你可以指定一个每个字母映射到什么值的数据结构。

#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") 
+0

一个问题,“let dictionary = dict table”是什么意思..特别是“dict”在这种情况下做了什么? – masfenix 2009-02-09 03:12:58

1

我发现了一种使用字符的ascii值来做这件事的方法,并且从那里获取数字,但我认为可能有更好的方法。

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

工作的优美,甚至更有效率,然后“映射”,但我想查看我问

感谢所有的解决方案。

1

所有你需要做的事情就是让字符串小写,像你所做的那样把它变成一个char数组,循环每个字母,取每个char的值并减去'a'的值并加一。这将使每个字母都具有在字母表中的位置值。

+0

是啊,这就是我想出了,但我学习的语言,所以我想如果有一种方法做一个“映射” – masfenix 2009-02-09 02:31:19

8

你有什么是体面的;这是另一个版本:

#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) 

它假设原始输入是大写。 “int”是一个将char(或其他)转换为int的函数; Seq.sum_by是完美的。

我还展示使用地图的一个例子,不知道你感兴趣的问题。

+0

三江源,我猜猜我现在会忘记“映射”.. – masfenix 2009-02-09 02:46:14

0

我意识到这是非常古老的,但我最近学习F#和玩这个问题的想法。也许有人会发现它有用:

let table = 
    Seq.zip ['A'..'Z'] (Seq.initInfinite((+) 1)) 
    |> Map.ofSeq 

let calc (input : string) = 
    let s = input.ToUpper() 
    match s with 
    | _ when Seq.forall System.Char.IsLetter s -> 
    Some (Seq.sumBy (fun c -> table.[c]) s) 
    | _ -> None 
0
let sumOfChar name =            // F# functional answer 
    name 
    |> List.ofSeq              // to char array 
    |> List.map (fun c -> int (System.Char.ToUpper c) - int 'A' + 1) // to value 
    |> List.fold (+) 0            // sum 

sumOfChar "Herb"             // 33 

// Or simply this version: 
let sumOfCharBy name = 
    let value c = int (System.Char.ToUpper c) - int 'A' + 1 
    List.sumBy value (List.ofSeq name) 

sumOfCharBy "HerbM"             // 46 

// or simply: 
let sumOfCharBy name = 
    name |> Seq.sumBy (fun c -> int (System.Char.ToUpper c) - int 'A' + 1) 

sumOfCharBy "HMartin"            // 83