代码之家  ›  专栏  ›  技术社区  ›  Tartar

F#检查列表是否为空

  •  1
  • Tartar  · 技术社区  · 7 年前

    作为一个F#新手,我正在尝试实现一个简单的函数,它将索引和列表作为参数,然后返回给定索引的列表值。

    let rec getElementAtIndex (index : int) (list : 'a list) = 
      match index, list with
        | _ ,[] -> failwith "index is greater than number of elements in list.."
        | _, _ when index < 0 -> failwith "index is less than 0." 
        | 0, (first::_) -> first
        | _, (_::rest') -> getElementAtIndex (index - 1) rest'
    

    | _ ,[] -> failwith "index is greater than number of elements in list."
    

    任何帮助都将不胜感激

    1 回复  |  直到 7 年前
        1
  •  4
  •   CaringDev    7 年前

    检查的模式 全球的 实际的 工作。通过这种方式,递归函数变得更简单,并且不需要 when 警卫或 length :

    let getElementAtIndex index list =
      if index < 0 then failwith "index is less than 0"
      if List.isEmpty list then failwith "list is empty"
      let rec get = function
        | _ , [] -> failwith "index is greater than number of elements in list"
        | 0, first::_ -> first
        | _, _::rest -> get(index - 1, rest)
      get(index, list)
    

    这个 function

      let rec get i l =
        match i, l with
        | _ , [] -> failwith "index is greater than number of elements in list"
        | 0, first::_ -> first
        | _, _::rest -> get (index - 1) rest
    

    更新

    if List.isEmpty list then failwith "list is empty" 你可以用 match list with [] -> failwith "..." | _ -> () if list = [] then failwith "..." 后者只适用于支持平等的元素列表。

    推荐文章