我在编写外观和递归说功能方面遇到了麻烦。它应该采用一个整数列表并评估一个整数列表,这些整数按照说出的方式读取。"例如,
look_and_say([1, 2, 2])
="一两二二十三" = [1, 1, 2, 2]
和
look_and_say([2, 2, 2])
="三个二十三" = [3, 2]
在整个递归调用过程中,我很难弄清楚如何在列表中添加元素(并跟踪列表)。
这是我写的一个应该有用的辅助功能:
fun helper(current : int, count : int, remainingList : int list) : int list =
if (current = hd remainingList) then
helper(current, count + 1, tl remainingList)
else
(* add count number of current to list *)
helper(hd remainingList, 1, tl remainingList);
这是我主要功能的粗略轮廓:
fun look_and_say(x::y : int list) : int list =
if x = nil then
(* print *)
else
helper(x, 1, y);
思想?
答案 0 :(得分:1)
你似乎有正确的想法,虽然它看起来好像你的助手永远不会终止。这是一种在没有助手的情况下实现它的方法。
fun look_and_say [] = []
| look_and_say (x::xs) =
case look_and_say xs of
[] => [1,x]
| a::b::L => if x=b then (a+1)::b::L
else 1::x::a::b::L
这是与助手一起实施的方法。
fun helper(current, count, remainingList) =
if remainingList = [] then
[count, current]
else if current = hd remainingList then
helper(current, count + 1, tl remainingList)
else count::current::look_and_say(remainingList)
and look_and_say [] = []
| look_and_say (x::y) = helper(x, 1, y)