SML:看说功能
SML: Look and Say Function
我在递归编写 look and say 函数时遇到问题。它应该获取一个整数列表并评估为一个整数列表 "reads as spoken." 例如,
look_and_say([1, 2, 2])
= "one one two twos" = [1, 1, 2, 2]
和
look_and_say([2, 2, 2])
= "three twos" = [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);
想法?
您的想法似乎是正确的,尽管看起来您的助手永远不会终止。这是一种无需助手即可实现的方法。
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)
我在递归编写 look and say 函数时遇到问题。它应该获取一个整数列表并评估为一个整数列表 "reads as spoken." 例如,
look_and_say([1, 2, 2])
= "one one two twos" = [1, 1, 2, 2]
和
look_and_say([2, 2, 2])
= "three twos" = [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);
想法?
您的想法似乎是正确的,尽管看起来您的助手永远不会终止。这是一种无需助手即可实现的方法。
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)