Recursion VDMSL递归函数序列的最小值
我认为这应该是相对简单的,我想知道是否有人知道如何回答这个问题: 定义一个递归函数seq min:N+->N,它返回自然数序列中的最小值 我在想一些关于Recursion VDMSL递归函数序列的最小值,recursion,sequence,formal-methods,vdm++,vdm-sl,Recursion,Sequence,Formal Methods,Vdm++,Vdm Sl,我认为这应该是相对简单的,我想知道是否有人知道如何回答这个问题: 定义一个递归函数seq min:N+->N,它返回自然数序列中的最小值 我在想一些关于 if hd seq < hd tl seq then seq-min([hd seq] concat tl tl seq) else if hd seq > hd tl seq then seq-min(tl seq) else if hd seq = hd tl seq then seq-min(tl seq) 如果hd-seq
if hd seq < hd tl seq then seq-min([hd seq] concat tl tl seq)
else if hd seq > hd tl seq then seq-min(tl seq)
else if hd seq = hd tl seq then seq-min(tl seq)
如果hd-seqhd tl序列,则序列最小值(tl序列)
否则,如果hd seq=hd tl seq,则seq min(tl seq)
谢谢你的帮助 类似的东西可能会起作用,但很难遵循——我们正在编写一个规范,因此如果它是明确的,它会有所帮助。以下是我的第一个想法。通过使用两个函数,它有点作弊,但我希望它相对清晰:
seq_min: seq of nat -> nat
seq_min(s) ==
minrec(tl s, hd s)
pre len s > 0;
minrec: seq of nat * nat -> nat
minrec(s, min) ==
if s = []
then min
else if hd s < min
then minrec(tl s, hd s)
else minrec(tl s, min);
以下是一种稍微不同的方法,使用单个函数:
seq_min: seq of nat -> nat
seq_min(s) ==
cases s:
[x] -> x,
[x] ^ rest ->
let min = seq_min(rest) in
if x < min then x else min
end
pre len s > 0;
seq_min:nat的seq->nat
序号(s)==
案例s:
[x] ->x,
[x] ^rest->
设最小值=顺序最小值(剩余)英寸
如果x0;
它的优点是简洁直观(而且功能单一)。当规范在这样的cases表达式中作为一组“模式”编写时,可以非常清楚,因为每个case都被明确地“解释”。您可以看到这方面的问题:因为它正在测试成对的值,并在列表的尾部递归,最终将传递一个值序列。此时,“hd tl seq”将失败。下面的答案通过递归传递最小值“down”并只测试头部,从而避免了对的需要。
seq_min: seq of nat -> nat
seq_min(s) ==
cases s:
[x] -> x,
[x] ^ rest ->
let min = seq_min(rest) in
if x < min then x else min
end
pre len s > 0;