【问题标题】:Function that checks that list one is the beginning of list 2检查列表 1 是否是列表 2 开头的函数
【发布时间】:2015-10-27 21:26:17
【问题描述】:

我正在尝试创建一个函数,它接受两个列表并检查第一个列表是否是第二个列表的开头。我有以下伪代码:

  • 一个空列表开始一个列表
  • 列表不会以空列表开头
  • 如果列表与第二个列表具有相同的头部和尾部,则它们会启动第二个列表

有人能解释一下解决这个问题的好方法吗?

对于第一个伪代码语句,我想这样做:

fun starts [] l2 = false |
    starts l1 [] = false |
    starts l1 l2 = if ((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)) then true 

我不完全确定如果第二个列表尾部比第一个列表尾部长,这是否会起作用?会发生错误吗?

如果有人可以帮助解释甚至找到解决方案,那就太好了!


编辑:

找到了一种方法,我不认为我离得太远了。

Fun start [] l2 = true |
start l1 [] = false |
start l1 l2 = if (hd(l1)) = (hd(l2)) then (start (tl(l1)) (tl(l2))) else false;

【问题讨论】:

  • 你的方法没问题。对于最后一行((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)),您希望进行递归调用以继续评估后续元素,直到您到达模式[] l2
  • 另外,不需要使用 if 语句。 ((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)) 等价于 if ((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)) then true else false。所以写if ((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)) then true 现在想办法从那时起继续递归调用。第一行也应该是真而不是假
  • oops.. 我的意思是说:所以写((hd(l1) = (hd(l2) andalso (tl(l1) = (tl(l2)) 现在想办法从那时起继续递归调用。另一个提示:您将 (tl(l1) = (tl(l2) 替换为其他内容,因为您需要一次比较一个元素。
  • 我最终设法得到它。我会更新代码。谢谢您的帮助!最后,我仍然使用了 if 语句,但可能会尝试不使用它。
  • 我现在正试图找出一个列表是否包含另一个列表的项目。您能否提出一个解决此问题的好方法?

标签: list sml tail head smlnj


【解决方案1】:

有模式匹配,但没有条件:

fun start [] l2 = true 
  | start l1 [] = false 
  | start (x::xs) (y::ys) = x = y andalso start xs ys

【讨论】:

  • 您介意看看我最近的问题吗?这是关于从另一个列表中删除一个列表。在我的帖子中更有意义。如果可以,那就太好了!谢谢。
猜你喜欢
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
相关资源
最近更新 更多