[英]why does F# complain when I write two yield! in one line?
This function concats two lists together: 此函数将两个列表合并在一起:
let append = fun a b -> [ yield! a
yield! b ]
append [1;2;3] [4;5;6]
val it : int list = [1; 2; 3; 4; 5; 6]
However, if I remove the space at the beginning of the list brackets in the function (like this [yield! ... ]
), it no longer works. 但是,如果删除函数中列表括号开头的空格(例如
[yield! ... ]
),它将不再起作用。
Also if I do the followings it complains: 另外,如果我执行以下操作,它也会抱怨:
[ yield! a yield! b ]
// or this
[ yield! a
yield! b]
The second yield! 第二产量! must be right under the first otherwise it complains.
必须在第一个之下正确,否则会抱怨。 Why?
为什么? I understand how yield!
我知道产量如何! works, but this seems a little weird to me that the syntax must be written exactly like this in this example.
可以工作,但是对我来说有点奇怪,语法必须在此示例中完全像这样编写。
In general, F# allows you to use indentation or explicit syntax in a number of places, including sequence expressions. 通常,F#允许您在许多地方(包括序列表达式)使用缩进或显式语法。 You can put both
yield!
你可以把两者都
yield!
constructs on a single line by adding a semicolon: 通过添加分号在一行上构造:
let append a b =
[ yield! a; yield! b ]
If you are using indentation, then F# requires the statements of sequence expression to be aligned - so your yield!
如果您使用缩进,则F#要求将序列表达式的语句进行对齐-这样就可以提高
yield!
constructs have to start at the same offset. 构造必须以相同的偏移量开始。 However, you do not have to indent them as far as in your first version.
但是,您不必像第一个版本那样缩进它们。 You can write:
你可以写:
let append a b =
[ yield! a
yield! b ]
Another, also valid, alternative syntax (which I personally do not find that nice, but which works too) is to put the opening [
on previous line and the closing ]
on a new line: 另一种也是有效的替代语法(我个人认为不是很好,但也可以使用)是将
[
开头的开行和结束的]
放在新行:
let append a b = [
yield! a
yield! b
]
Note that I also replaced your let append = fun ab ->
with an inline function definition let append ab
- you can put the parameters immediately after the function name, rather than creating an explicit function using fun
. 请注意,我还用内联函数定义替换了
let append = fun ab ->
let append ab
您可以将参数立即放在函数名称之后,而不是使用fun
创建显式函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.