我正在上OCaml的MOOC课程,并将其作为家庭作业问题,涉及仅使用5个concat运算符“ ^”来连接字符串,并创建一个结果字符串,该字符串具有9个原始字符串,并用“,”隔开“。
即使我设法通过以下解决方案解决了该问题,但我仍然认为代码不够好/我不了解使用局部定义的概念。
let sentence = (let word3 = (let word2 = (let word1= word ^ "," in
let word2 = word1 ^ word1 in word2) in
let word3 = word2 ^word2 in word3) in
let word4 = word3 ^ word3 in word4) ^ word;;
请通过更好的解决方案帮助我理解概念。请记住,您只能使用5个concat运算符。
答案 0 :(得分:0)
需要指出的是这个表达式:
let a = b in a
等效于以下表达式:
b
如果在代码中进行此替换,则会得到以下内容:
let sentence =
(let word3 =
(let word2 =
(let word1 = word ^ "," in word1 ^ word1)
in
word2 ^ word2)
in
word3 ^ word3) ^ word
这是非常合理的代码。由于嵌套,很难遵循。您已经像这样嵌套let ... in
:
let a =
let b = 3 in
b * b
in
a + 7
但是您可能会有更多类似的东西:
let b = 3 in
let a = b * b in
a + 7
如果您对代码进行了更改,则会得到以下信息:
let word1 = word ^ "," in
let word2 = word1 ^ word1 in
let word3 = word2 ^ word2 in
let sentence = word3 ^ word3 ^ word
更新
请注意,这等效于您的代码,但不是完整的表达式。如果要对其进行测试,请将其添加到末尾:
in sentence