Q1:我想在VisualStudio2019中在*.fsx中的多行设置F#函数的格式,但当我尝试时,会出现语法错误。(见下文)
Q2:在Haskell中(我记得),声明函数的顺序并不重要。在F#中也是如此吗?
(*
2.3 Declare the F# function
isIthChar: string * int * char -> bool
where the value of isIthChar(str,i,ch) is true
if and only if ch is the i’th character in the string str
(numbering starting at zero).
Hansen, Michael R.. Functional Programming Using F# (p. 39). Cambridge University Press. Kindle Edition. *)
let isIthChar (str: string, i, ch) = (ch = str.[i])
(*
2.4 Declare the F# function
occFromIth: string * int * char -> int where
occFromIth(str, i, ch) =
the number of occurances of character ch
in positions j in the string str
with j >= i
Hint: the value should be 0 for i ≥ size str.
Hansen, Michael R.. Functional Programming Using F# (p. 39). Cambridge University Press. Kindle Edition.
*)
let rec countChar(str, i, j, ch, cnt) = if j < i then cnt else if isIthChar(str, j, ch) then countChar(str, i, j - 1, ch, cnt + 1) else countChar(str, i, j - 1, ch, cnt);; // all one line
let occFromIth(str, i, ch) = if (i >= String.length str) then 0 else countChar(str, i, (String.length str) - 1, ch, 0);; // all one line
//WANT something like:
let rec countChar(str, i, j, ch, cnt) = if j < i
then cnt
else if isIthChar(str, j, ch)
then countChar(str, i, j - 1, ch, cnt + 1)
else countChar(str, i, j - 1, ch, cnt);;
let occFromIth(str, i, ch) = if (i >= String.length str)
then 0
else countChar(str, i, (String.length str) - 1, ch, 0);;
// but these give syntax errors.
(* 2.5 Declare the F# function occInString: string * char -> int where
occInString(str, ch) = the number of occurences of a character ch in the string str.
Hansen, Michael R.. Functional Programming Using F# (p. 39). Cambridge University Press. Kindle Edition. *)
let occInString(str, ch) = occFromIth(str, 0, ch)发布于 2020-10-09 03:40:22
格式: then和else必须至少与其前面的if一样向右,但在这两种情况下,它们都是向左的。只需将if移动到下一行:
let rec countChar(str, i, j, ch, cnt) =
if j < i
then cnt
else if isIthChar(str, j, ch)
then countChar(str, i, j - 1, ch, cnt + 1)
else countChar(str, i, j - 1, ch, cnt)还请注意,如果代码位于fsx文件中,而不是从键盘键入FSI,则不需要双分号。
声明顺序:与Haskell不同,在F#中,所有名称都必须在使用之前定义,所以您的程序从上到下进行读取。乍一看,这似乎是有限的,但在实践中,它对代码的可读性有很大的帮助。
此规则的一个例外是一组相互递归的函数(或类型):
let rec f x = g (x+1)
and g x = f (x-1)在本例中,在定义g之前使用它。
最近,F#还获得了递归模块,其中所有定义都被认为是一个大型递归组:
module rec A =
let f x = g (x+1)
let g x = f (x-1)一些与你的问题无关的笔记:
else if可以缩写为elifcountChar(str, i, j, ch, cnt),习惯上(在实践中更方便)用countChar str i j ch cnt格式对参数进行定义
https://stackoverflow.com/questions/64273521
复制相似问题