Flattening only one level of a list in Prolog

后端 未结 1 1379
花落未央
花落未央 2020-12-21 07:29

I\'m working on a problem to flatten only one level of a list in Prolog. For example, [[1],[2,3]] would become [1,2,3], but [[1,[2]],3]

相关标签:
1条回答
  • 2020-12-21 07:54

    You need 3 simple clauses, I will show just the most complex one

    flat([H|T],R) :- is_list(H), flat(T,T1), append(H,T1,R).
    

    other two clauses are the base recursion case, and a copy as is of head to result.

    You should also place a cut in the clause I've shown, otherwise on backtracking you'll get wrong results (due to firing of the clause copy as is)

    0 讨论(0)
提交回复
热议问题