return 给定列表中的字符串,单词之间有空格 - sml
return string from given list with spaces between words - sml
我必须编写一个 SML 函数,returns 由给定列表中以空格分隔的单词组成的句子。我必须至少使用 foldl/foldr/map 函数之一。
这是我写的:
fun add_spaces nil = ""
| add_spaces(x::xs) = foldr (fn (x,xs) => (add_spaces x)^" "^xs) x [xs];
add_spaces(["Testing","function","with","this","sentence"]);
但是那个函数带来了一个反转的字符串(用函数测试来判断这个)。我在网上看到可以通过反转列表来解决([xs] 在这种情况下对吗?)但是我该怎么做呢?
谢谢
您的函数 add_spaces
使用 foldr
的方式非常复杂但可能会被误解。
常规递归函数,不满足使用foldl/foldr/map的标准,是,
fun add_spaces [] = ""
| add_spaces [s] = s
| add_spaces (s::ss) = s ^ " " ^ add_spaces ss
依赖折叠进行递归的类似函数将遵循一种模式,
fun add_spaces [] = ""
| add_spaces (s1::ss) = fold<l/r> (fn (s,res) => ...) s1 ss
其中 ...
明确 而不是 引用 add_spaces
。因此,您至少有两种工具来指导您的物品到达的顺序。一个是您在上述模板的匿名函数中引用 s
和 res
的顺序,另一个是您选择 foldl
和 foldr
.
还要注意 foldl
和 foldr
将从不同的方向遍历列表;分别从左边和右边。为了说明顺序,尝试折叠会导致副作用的东西,看看哪些效果先到达:
- foldl (fn (s, _) => print (s^"\n")) () ["Hello", "World!"];
Hello
World!
> val it = () : unit
- foldr (fn (s, _) => print (s^"\n")) () ["Hello", "World!"];
World!
Hello
我必须编写一个 SML 函数,returns 由给定列表中以空格分隔的单词组成的句子。我必须至少使用 foldl/foldr/map 函数之一。
这是我写的:
fun add_spaces nil = ""
| add_spaces(x::xs) = foldr (fn (x,xs) => (add_spaces x)^" "^xs) x [xs];
add_spaces(["Testing","function","with","this","sentence"]);
但是那个函数带来了一个反转的字符串(用函数测试来判断这个)。我在网上看到可以通过反转列表来解决([xs] 在这种情况下对吗?)但是我该怎么做呢?
谢谢
您的函数 add_spaces
使用 foldr
的方式非常复杂但可能会被误解。
常规递归函数,不满足使用foldl/foldr/map的标准,是,
fun add_spaces [] = ""
| add_spaces [s] = s
| add_spaces (s::ss) = s ^ " " ^ add_spaces ss
依赖折叠进行递归的类似函数将遵循一种模式,
fun add_spaces [] = ""
| add_spaces (s1::ss) = fold<l/r> (fn (s,res) => ...) s1 ss
其中 ...
明确 而不是 引用 add_spaces
。因此,您至少有两种工具来指导您的物品到达的顺序。一个是您在上述模板的匿名函数中引用 s
和 res
的顺序,另一个是您选择 foldl
和 foldr
.
还要注意 foldl
和 foldr
将从不同的方向遍历列表;分别从左边和右边。为了说明顺序,尝试折叠会导致副作用的东西,看看哪些效果先到达:
- foldl (fn (s, _) => print (s^"\n")) () ["Hello", "World!"];
Hello
World!
> val it = () : unit
- foldr (fn (s, _) => print (s^"\n")) () ["Hello", "World!"];
World!
Hello