gpt4 book ai didi

sml - 如何从 SML 中的日期列表中获取最早的日期?

转载 作者:行者123 更新时间:2023-12-02 22:15:47 24 4
gpt4 key购买 nike

我在完成这项作业时遇到了一些麻烦。这就是教授的要求:

Write a function oldest that takes a list of dates and evaluates to an (int*int*int) option. It evaluates to NONE if the list has no dates and SOME d if the date d is the oldest date in the list.

我知道如何创建该函数并且对如何使用日期列表有一些想法,但我不知道如何“存储”最旧的值以将其与日期列表的尾部进行比较。这是我提交的(它不起作用,它总是检索第一个日期,但我真的很想知道答案)

fun oldest (datelist : (int * int * int) list) =
if null datelist
then NONE
else if null (tl datelist) then
SOME (hd datelist)
else let val date = if is_older (hd datelist, hd (tl datelist)) then SOME (hd datelist) else SOME (hd (tl datelist))
in oldest(tl datelist)
end

最佳答案

在递归调用中保持值的一种方法是在参数中传递它。由于您无法更改原始函数,因此最常用的解决方案是使用一个辅助函数来接受这个额外的参数,以及可能的其他参数。
这样的辅助函数可以获取列表的头部并将其与额外参数进行比较,在列表尾部的递归调用中使用两者中最旧的参数。然后当列表为空时,您只需返回这个额外的参数,因为它必须是最旧的。

fun oldestOfTwo (d1, d2) = (* return the oldest/minimum of the two dates *)

fun oldest [] = NONE
| oldest (d::ds) =
let
fun oldest' max [] = SOME max
| oldest' max (d::ds) =
oldest (oldestOfTwo (max, d2)) ds
in
oldest' d ds
end

另一种解决方案可能是取出列表的前两个元素,放回两个中最旧的元素,因此在每次递归调用中,您都会删除列表中的一个元素,并且在某些时候,列表中只会有一个元素列表,它必须是最旧的。

fun oldest [] = NONE
| oldest [d] = SOME d
| oldest (d1 :: d2 :: ds) = oldest (oldestOfTwo (d1, d2) :: ds)

关于sml - 如何从 SML 中的日期列表中获取最早的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14501720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com