我收到了这个函数的错误。我是f#的新手,所以我不完全知道代码在做什么,我尝试复制一个只需一个参数就能在字符串中找到元音的函数。
let rec countDigraph c1 c2 L =
match L with
| [] -> 0
| hd::tl when hd = c1 -> 1 + count c1 tl
| hd::tl when tl = c2 -> 1 + count c2 tl
| _::tl ->0 + countDigraph c1 c2 tl在代码中稍后调用:
let printCountDigraph digraph L =
let c1 = List.head digraph
let c2 = List.head digraph
printfn "%A,%A: %A" c1 c2 (countDigraph c1 c2 L)
let digraphs = [['a';'i']; ['c';'h']; ['e';'a']; ['i';'e']; ['o';'u']; ['p';'h']; ['s';'h']; ['t';'h']; ['w';'h'];]
List.iter (fun digraph -> printCountDigraph digraph L) digraphs发布于 2022-10-14 22:24:28
在countDigraph中,您需要检查列表的前两个字符是否与有向图匹配。您似乎试图通过首先检查第一个(第一个),然后检查第二个(第二个),但这不是模式匹配的工作方式。
最简单的选择是使用模式l1::l2::tl提取前两个字母的单个子句,然后是列表的其余部分。您需要考虑一下,例如,eai是两个有向图还是一个。如果是两个,则需要按下面的方式递归调用c2::tl上的countDigraph --如果只有一个,则只需在tl上递归调用countDigraph。
let rec countDigraph c1 c2 L =
match L with
| [] -> 0
| l1::l2::tl when l1=c1 && l2=c2 -> 1 + countDigraph c1 c2 (c2::tl)
| _::tl ->0 + countDigraph c1 c2 tl如果将有向图表示为成对列表,而不是由两个元素列表组成的列表,则代码的其余部分变得容易得多:
let printCountDigraph (c1, c2) L =
printfn "%A,%A: %A" c1 c2 (countDigraph c1 c2 L)
let digraphs = [('a','i'); ('c','h'); ('e','a'); ('i','e');
('o','u'); ('p','h'); ('s','h'); ('t','h'); ('w','h')]
let L = List.ofSeq "chai"
List.iter (fun digraph -> printCountDigraph digraph L) digraphshttps://stackoverflow.com/questions/74075100
复制相似问题