繁体   English   中英

如何在OCaml中创建一个字典,将第一个列表中每个元素的出现次数与第二个列表中的每个元素相关联?

[英]How do I create a dictionary in OCaml that associates to each element of the first list the number of its occurences in the second list?

我有两个列表,[“ 0”,“ 1”]和[“ 0”,“ 1”,“ 0”],我想得到一个列表,[(0,2),(1,1)] ,-将第一个列表中每个元素的出现次数关联到第二个列表中。 我尝试了这个:

let partialSolution = 
List.map(
    fun x -> 
        let subsubList = List.for_all  (fun y -> (String.compare x y)=0) ) ("0"::("1"::("0"::[]))) in
 (x, List.length ( List.filter ( fun z -> z = true) subsubList ) ) 
) ;;

,但不好:它给了我这些错误:

# let partialSolution = 
# List.map(
#     fun x -> 
#         let subsubList = List.for_all  (fun y -> (String.compare x y)=0) )
File "", line 4, characters 73-74:
Error: Syntax error: operator expected.
#  ("0"::("1"::("0"::[]))) in
File "", line 4, characters 99-101:
Error: Syntax error
#  (x, List.length ( List.filter ( fun z -> z = true) subsubList ) ) 
# )
File "", line 6, characters 0-1:
Error: Syntax error
#  ;;
File "", line 6, characters 2-4:
Error: Syntax error

我想了解如何解决此问题-我是OCaml的新手。

您对括号有点狂热。 语法错误是由(fun y -> ...)之后的多余右括号引起的。

但是您仍然会遇到类型错误,因为List.for_all返回bool ,如果所有项目都满足谓词,则返回trueList.for_all返回false 看来您想在这里使用List.map

您也不需要在括号中用::括起所有用法。 ("0"::"1"::"0"::[])很好,但是您也可以将其简化为简单的列表文字: ["0"; "1"; "0"] ["0"; "1"; "0"] ["0"; "1"; "0"] 另外, z = true等效于z ,尽管可读性可能略低。

这样编译。 我还没有检查它是否确实满足您的要求:

let partialSolution = 
    List.map
        begin fun x -> 
            let subsubList =
                List.map
                    (fun y -> String.compare x y = 0)
                    ["0"; "1"; "0"]
            in
            (x, List.length (List.filter (fun z -> z) subsubList)) 
        end

另外,如果您使用的是4.03或更高版本,则可以使用String.equal ;如果您使用的是4.08,则可以使用Fun.id而不是临时lambda函数:

let partialSolution = 
    List.map
        begin fun x -> 
            let subsubList =
                List.map (String.equal x) ["0"; "1"; "0"]
            in
            (x, List.length (List.filter Fun.id subsubList)) 
        end

或者,您可以使用List.fold_left直接进行计数,而不是处理中间的bool list

let partialSolution = 
    List.map
        begin fun x -> 
            let count =
                List.fold_left
                    (fun count y ->
                        if String.compare x y = 0 then
                            count + 1
                        else
                            count)
                    0 ["0"; "1"; "0"]
            in
            (x, count) 
        end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM