【问题标题】:how to split a list into two lists in which the first has the positive entries and the second has non-positive entries-SML如何将列表拆分为两个列表,其中第一个具有正条目,第二个具有非正条目-SML
【发布时间】:2017-10-13 05:14:18
【问题描述】:

我是 SML 的新手,我想编写一个函数 splitup :int list -> int list * int list 给定一个整数列表,它从两个整数列表创建,一个包含非负条目,另一个包含负条目。 这是我的代码:

fun splitup (xs :int list) =
  if null xs
  then ([],[])
  else if hd xs < 0
  then hd xs :: #1 splitup( tl xs)
  else hd xs :: #2 splitup( tl xs)

这是我得到的警告:

ERROR : operator and operand don't agree
ERROR : types of if branches do not agree

函数 splitup(tl xs) 应该返回 int list * int list 所以我认为我的递归应该没问题。 有什么问题,我该如何解决?

【问题讨论】:

    标签: functional-programming sml smlnj


    【解决方案1】:

    问题是

    hd xs :: #1 splitup( tl xs)
    

    hd xs :: #2 splitup( tl xs)
    

    是列表——你可以从:: 中看出——而不是结果应该是的列表对。

    对于非空的情况,你需要先拆分列表的其余部分,然后将头部附加到结果的正确部分,并将结果的另一部分成对添加。
    习惯模式匹配也是一个好主意,因为它可以简化代码量。

    类似这样的:

    fun splitup [] = ([], [])
      | splitup (x::xs) = let (negatives, non_negatives) = splitup xs
                          in if x < 0 
                             then (x :: negatives, non_negatives)
                             else (negatives, x :: non_negatives)
                          end
    

    【讨论】:

    • 当我的递归到达列表末尾时,它返回列表对,#1 splitup (xs) 应该是一个列表。那么为什么:: #1 pairs of lists 会出错呢?
    • @DennngP 它出错了,因为它应该是一对列表。正如消息所说,条件的两个分支必须具有相同的类型。
    【解决方案2】:

    已经有List.partition: ('a -&gt; bool) -&gt; 'a list -&gt; 'a list * 'a list,一个执行此操作的高阶库函数。如果您想将整数拆分为(负数、非负数):

    val splitup = List.partition (fn x => x < 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2013-04-15
      相关资源
      最近更新 更多