Seq.Map string->string
全部!
这段代码有什么问题?我无法理解我对 Seq.Map 做错了什么。 这是错误消息:类型“unit”与类型“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上有什么可以理解的例子吗?
来自 wiki 的 PS 示例(有效):
(* 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
all!
What is wrong with this code? I cannot understand what I am doing wrong with Seq.Map.
Here is the error message: The type 'unit' is not compatible with the type '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")
Is there any understandable examples on Seq.Map?
PS Example from wiki (it works):
(* 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑问题实际上是您之前的通话造成的。
Seq.iter
不返回任何内容(或者更确切地说,返回unit
),因此您不能在管道中间使用它。试试这个:...然后,如果您确实需要打印出“找到的库”行,您可以添加另一个执行打印并仅返回输入的映射:
这很可能是无效的 F#,但我认为 目标是正确的:)
I suspect the problem is actually your previous call.
Seq.iter
doesn't return anything (or rather, returnsunit
) so you can't use it in the middle of a pipeline. Try this:... and then if you really need to print out the "libs found" line, you can add another mapping which performs the printing and just returns the input:
This may well be invalid F#, but I think the aim is right :)
WebSharper 包含一个您可以自己定义的运算符,如下所示:
允许您调用
'a ->; 类型的函数返回相同值的输入值上的单位
。修复你的代码只需要稍微修改一下:
另一方面,你最终会迭代集合两次,这可能不是你想要的。
更好的方法是定义一个函数 Do(小写
do
是 F# 中的保留关键字),它会在迭代序列时产生副作用。 Rx.NET (Ix) 在 EnumerableEx 中提供了这样的函数:然后你可以像这样引入副作用:
只有在迭代最后一行的集合时才会引入副作用。
WebSharper includes an operator you can define yourself like this:
Allowing you to call a function of type
'a -> unit
on the input value returning the same value.Fixing your code would require but a slight modification:
On the other hand you would end up iterating the collection twice which might not be what you want.
A better approach would be to define a function Do (lowercase
do
being a reserved keyword in F#) which introduces a side effect on iterating the sequence. Rx.NET (Ix) provides such a function in EnumerableEx:and then you can introduce the side effect like so:
The side effect will be introduced only upon iterating the collection on the last line.