简体   繁体   English

prolog 中列表的运行长度解码?

[英]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).
  • you are asked to handle a list of 'tuples' of 2 elements, not a list of lists of 2 elements您被要求处理 2 个元素的“元组”列表,而不是 2 个元素列表的列表
  • then, the test in the second clause will always fail那么,第二个子句中的测试将始终失败
  • the tuples elements are key and value , but you're 'accessing' them in inverse order.元组元素是keyvalue ,但您以相反的顺序“访问”它们。

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.

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