views:

49

answers:

3

Hey, im trying to declare a function, string list -> string, that with the input for instance ["Chicago","city","USA"] should return "Chigago city USA". And im having a bit of trouble, 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"

Any hints is appreciated :)

+1  A: 

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.

sepp2k
i cant really get it to work, i made a new function fun hj ts = fn(a,b) => (a^" "^b);
@user: Not sure what the `ts` is for since you don't use it. You can just do `val hj = fn (a,b) => (a^" "^b)` or `fun hj (a,b) = (a^" "^b)`, which is the same, but shorter. Then `foldr hj "" ts`, works fine.
sepp2k
Ah ofcourse, thanks a bunch. Is there a short way around removing the last space that occurs?
perhaps instead of fun hj (a,b) = (a^" "^b) i could use something like fun hj (a,_) = a | (a,b) => a^" "^b); ?
yes that works, but with (a,"") instead of (a,_) thanx for the help mate:)
@user: Yes, exactly, except that `_` does not mean "empty string". If you replace `_` with `""` (which does mean "empty string"), it will work.
sepp2k
@user: Do consider clicking the green check mark next to my answer to indicate that it solved your problem.
sepp2k
.......done! ;)
A: 

should it be like this then?? or...

fun hj (a,b) = (a^" "^b) | foldr hj "" ts

or ????

thnx.

peter81
A: 

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
- 
Frayser