问题
I'm trying to declare a function, string list -> string, that with the input for instance
["Chicago","city","USA"] should return "Chicago city USA". What I did so far was this:
fun gather ts = foldr op ^ "" ts;
This seems to be somewhat along the lines, however the problem is, I would like to include the spaces between the words, as this function would return "ChigagocityUSA".
回答1:
Yes, the problem is that ^ is a function that for two strings "foo" and "bar" returns "foobar", although you want "foo bar".
So what you need to do is to define a function that takes two string arguments (as a tuple) and returns the two strings with a space in between them (so string1 ^ " " ^ string2).
You can then give that function as an argument to foldr and get the result you want.
回答2:
Use hd and tl to get inital values for fold. This avoids having a leading or trailing blank character in the result. foldl is useful if you want to think left-to-right.
Definition:
fun gather xs =
foldl (fn (x,acc) =>
acc ^ " " ^ x) (hd xs) (tl xs)
Usage:
- gather ["what", "is", "this", "gather"];
val it = "what is this gather" : string
-
来源:https://stackoverflow.com/questions/3900369/concatenating-strings-with-foldr-in-sml