[英]Types mismatch when building list in F#
I am trying to build a list from the names of some files. 我正在尝试从某些文件的名称构建一个列表。 Unfortunately I am getting a type error that I do not know how to correct.
不幸的是,我收到一个我不知道如何纠正的类型错误。
My code:- 我的代码:-
open System
let buildStringList (list: string []) =
let initial = []
for i = 0 to list.Length do
let foo = list.[i]
List.append initial foo.Substring(foo.IndexOf("."))
The type error:- 类型错误:
error FS0001: This expression was expected to have type string -> 'a
but here has type string
And this relates to the "foo.Substring(foo.IndexOf("."))" object. 这与“ foo.Substring(foo.IndexOf(“。”))“对象有关。 What is the best way to get the types correct here?
在这里使类型正确的最佳方法是什么?
Many thanks. 非常感谢。
Indentation of your function is totally off. 函数的缩进完全不可用。 At any rate,
foo.Substring(foo.IndexOf("."))
is a string
which isn't of type list
as required by List.append
. 无论如何,
foo.Substring(foo.IndexOf("."))
是一个string
,其类型为不是list
所要求的List.append
。
What you want is to add an element to an accumulator list. 您想要的是将元素添加到累加器列表。 A quick fix on your function is using a
mutable
value: 对函数的快速修复是使用
mutable
值:
let buildStringList (arr: string []) =
let mutable result = []
for i = 0 to arr.Length do
let foo = arr.[i]
result <- foo.Substring(foo.IndexOf("."))::result
List.rev result // Use List.rev if you would like to keep the original order
However, the recommended way is to use high-order functions. 但是,推荐的方法是使用高阶函数。 While using
List.map
as Mark's answer is a good approach, you can use Array.fold
which is closer to your code: 虽然使用
List.map
作为Mark的答案是一个很好的方法,但是可以使用更接近代码的Array.fold
:
let buildStringList (arr: string []) =
arr
|> Array.fold (fun acc foo -> foo.Substring(foo.IndexOf("."))::acc) []
|> List.rev
To be complete, list comprehension is also helpful in certain situations: 为了完整起见,列表理解在某些情况下也很有帮助:
let buildStringList (arr: string []) =
[ for foo in arr -> foo.Substring(foo.IndexOf(".")) ]
I think this is a more functional way to do what you're trying: 我认为这是您尝试的功能更实用的方法:
open System
let buildStringList (list: string []) =
list |> Array.toList |> List.map (fun x -> x.Substring(x.IndexOf(".")))
The reason for your particular error was that List.append takes two lists, not a list and a single item. 发生特定错误的原因是List.append包含两个列表,而不是一个列表和一个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.