【问题标题】:List of lists, lamba and filtering results列表、lamba 和过滤结果列表
【发布时间】:2017-06-25 02:17:38
【问题描述】:

我想创建两个函数: 1) 函数在列表 (int list list) 中查找所有小于零的元素,然后将这些元素作为 (int list) 类型的列表返回。

2) 查找列表中所有偶数的函数(浮点列表列表),然后将它们作为(整数列表)返回。

它们都应该使用至少一个 lambda 表达式(fun x -> ...)。

如何创建这些函数?老实说我不知道​​。

let findnegative(d:int list list)=
  //maybe    List.map

let findeven (t:float list list) = 
 //something with     List.filter (fun x -> x%2.0 = 0.0)

【问题讨论】:

  • 使用list |> List.collect id 将其从列表列表转换为列表。然后根据您的情况申请List.filter。
  • @Asti - 您实际上可以使用List.filter ... 而不是id 作为List.collect 的参数,一步完成。
  • 您尝试做些什么来解决这个问题?
  • @kvb let findeven(t:float list list) = List.map(fun x -> int(x)) (List.filter (fun x -> x%2.0 = 0.0) t)但它不起作用(“浮动与浮动列表不匹配”错误)
  • 还不错...你知道这个|> 运算符是什么吗?

标签: lambda f# functional-programming


【解决方案1】:

我认为您正在寻找这样的东西:

let findnegative(d:int list list) =
  d
  |> List.map (fun x -> x |> List.filter (fun y -> y < 0))
  |> List.collect id

let findeven (t:float list list) = 
  t
  |> List.map (fun x -> x |> List.filter (fun y -> y % 2.0 = 0.0))
  |> List.collect id
  |> List.map int

这可以简化为:

let findnegative =
  List.collect <| List.filter ((>)0)

let findeven = 
  List.collect <| List.filter (fun x -> x % 2. = 0.) >> List.map int

【讨论】:

  • 这对我来说很奇怪x % 2. = 0.
  • 是的,我在几分钟前改回来了。我对其他语法的理解不太正确,我正在调查。
  • 啊,当我部分申请 ((%)2.) 时,2. 在操作员的错误一侧。我相信需要fun 语法。
  • 借助一个简单的帮助函数flip 可以降低可读性;):let findeven = let inline flip f l r = f r l in List.collect &lt;| List.filter (flip (%) 2.0 &gt;&gt; (=) 0.) &gt;&gt; List.map int
  • % 对于浮点数,我是认真的 :)
猜你喜欢
  • 2021-12-06
  • 2019-08-13
  • 2013-07-04
  • 2021-11-14
  • 1970-01-01
  • 2023-02-25
  • 2015-02-02
  • 2012-06-18
  • 1970-01-01
相关资源
最近更新 更多