繁体   English   中英

Seq.Map 字符串->字符串

[英]Seq.Map string->string

全部!

这段代码有什么问题? 我无法理解我对 Seq.Map 做错了什么。 这是错误消息:“单元”类型与“seq<'a>”类型不兼容

let getPathToLibFile value =
    let regex = new Regex("\"(?<data>[^<]*)\"")
    let matches = regex.Match(value)
    matches.Value

let importAllLibs (lines:string[]) =
    lines
    |> Seq.filter isImportLine
    |> Seq.iter (printfn "Libs found: %s")
    |> Seq.map getPathToLibFile // error in this line
    |> Seq.iter (printfn "Path to libs: %s")

Seq.Map 上有什么可以理解的例子吗?

PS来自wiki的示例(有效):

(* Fibonacci Number formula *)
let rec fib n =
    match n with
    | 0 | 1 -> n
    | _ -> fib (n - 1) + fib (n - 2)

(* Print even fibs *)
[1 .. 10]
|> List.map     fib
|> List.filter  (fun n -> (n % 2) = 0)
|> printlist

我怀疑问题实际上是您之前的电话。

Seq.iter不返回任何内容(或者更确切地说,返回unit ),因此您不能在管道中间使用它。 尝试这个:

let importAllLibs (lines:string[]) =
    lines
    |> Seq.filter isImportLine
    |> Seq.map getPathToLibFile
    |> Seq.iter (printfn "Path to libs: %s")

...然后,如果您确实需要打印出“找到的库”行,则可以添加另一个执行打印并仅返回输入的映射:

let reportLib value =
    printfn "Libs found: %s" value
    value

let importAllLibs (lines:string[]) =
    lines
    |> Seq.filter isImportLine
    |> Seq.map reportLib
    |> Seq.map getPathToLibFile
    |> Seq.iter (printfn "Path to libs: %s")

这很可能是无效的F#,但我认为目标是对的:)

WebSharper 包含一个运算符,您可以像这样定义自己:

let (|!>) a f = f a; a

允许您在返回相同值的输入值上调用类型为'a -> unit的 function。

修复您的代码只需要稍作修改:

lines
|> Seq.filter isImportLine
|!> Seq.iter (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")

另一方面,您最终会迭代集合两次,这可能不是您想要的。

更好的方法是定义一个 function Do(小写的do是 F# 中的保留关键字),这会对迭代序列产生副作用。 Rx.NET (Ix) 在 EnumerableEx 中提供了这样一个 function:

let Do f xs = Seq.map (fun v -> f v; v) xs

然后你可以像这样介绍副作用:

lines
|> Seq.filter isImportLine
|> Do (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")

只有在最后一行迭代集合时才会引入副作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM