Concatenating strings with foldr in SML

痴心易碎 提交于 2019-12-11 03:03:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!