简体   繁体   English

包含在OCaml开头的列表的过滤器

[英]A filter that contain a list in the beginning in OCaml

I want to create a function that return the next number in binary form. 我想创建一个以二进制形式返回下一个数字的函数。 For example : 例如 :

000 -> 001 -> 010 -> 011 -> 100 -> 101 -> 110 -> 111. My function is : 000-> 001-> 010-> 011-> 100-> 101-> 110->111。我的功能是:

let rec next_number = function 
             | [] -> []
             | (a,b)::[] -> if b = 0 then (a,1)::[] else (a,0)::[]
             | l::(a,value1)::(b,value2)::[] -> if (value2 = 0) then l::(a,value1)::(b,1)::[]
                                                else
                                                    begin
                                                         if value1 = 0 then l::(a,1)::(b,0)::[]
                                                         else (next_number l)::(a,0)::(b,0)::[]
                                                    end
             ;;

When I compile I got the error : This expression (l in l::(a,value1)::(b,value2)::[]) has type 'a * int but an expression was expected of type ('a * int) list 编译时出现错误:该表达式(l在l ::((a,value1)::( b,value2):: []中)的类型为'a * int,但期望的表达式类型为('a * int)清单

How to tell OCaml that the filter is a list then a couple then couple then an empty list not 3 couples and then empty list. 如何告诉OCaml过滤器是一个列表,然后是一对,然后是一对,然后是一个空列表,而不是3对,然后是空列表。

Thanks for your help. 谢谢你的帮助。

There's no pattern that matches a prefix of a list. 没有与列表前缀匹配的模式。 If you imagine a value as a tree, a pattern always matches a full subtree starting at some point. 如果您将值想象为树,则模式总是从某个点开始匹配完整的子树。 The prefix of a list doesn't have this form. 列表的前缀没有这种形式。 When you pick out the full subtree you get the whole list. 当您选择完整的子树时,您将获得整个列表。

If your algorithm needs to work from the back of the list toward the front, you may want to reverse the list before starting. 如果您的算法需要从列表的后面到列表的前面工作,则可能需要在开始之前反转列表。

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

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