[英]run length decoding of a list in prolog?
I'm trying to decode a given list for example mydecode([(a,1), (b,2), (c,3), (d,2)],X) should give X = ['a','b','b','c','c','c','d','d'].我正在尝试解码给定的列表,例如 mydecode([(a,1), (b,2), (c,3), (d,2)],X) 应该给出 X = ['a', 'b','b','c','c','c','d','d']。 What is the error in this code?这段代码有什么错误?
mydecode([],[]).
mydecode([X|Ys],[X|Zs]) :- \+ is_list(X), mydecode(Ys,Zs).
mydecode([[1,X]|Ys],[X|Zs]) :- mydecode(Ys,Zs).
mydecode([[N,X]|Ys],[X|Zs]) :- N > 1, N1 is N - 1, mydecode([[N1,X]|Ys],Zs).
key
and value
, but you're 'accessing' them in inverse order.元组元素是key
和value
,但您以相反的顺序“访问”它们。 So, remove the second clause - it's irrelevant, since pattern matching will discard ill formed lists.因此,删除第二个子句——它无关紧要,因为模式匹配将丢弃格式不正确的列表。 Change the [1,X]
to (X,1)
and similarly other references to tuples, and test your code with the query assigned.将[1,X]
更改为(X,1)
以及类似的其他对元组的引用,并使用分配的查询测试您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.