开发者

How do I iterate a list?

I am trying to do basi开发者_StackOverflowc list operations with SML.

I want to extract each element of the list and append string to that element and add it back to the list. Example:

List : [A,B,C,D]
String : A
Final List: [AA,AB,AC,AD]

How can I iterate through each element in the list in SML? I can append strings using ^ and concatenate lists using @ but how do I extract each element from the list?

Also can we use something like map or arrays to store these list values and pass it to different functions in SML?

I could just find some vague information about map and no definite information as to how we can use it.


two easy ways to do this:

- fun addstring (x::xs) a = (a^x) :: addstring xs a  
=   | addstring []      a = []  
=   ;  
val addstring = fn : string list -> string -> string list  
- addstring ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

The above uses pattern matching to destruct the list, performs the operation, then constructs the list again, recursing as it goes.

- fun addstring2 xs a = map (fn x => a^x) xs;  
val addstring2 = fn : string list -> string -> string list  

- addstring2 ["A", "B", "C", "D"] "A";  
val it = ["AA","AB","AC","AD"] : string list  

This one is a fair bit simpler (if perhaps a tiny bit harder to read than the explicit cases in addstring.) but it shows how map is used - you specify a function that maps each element from the source to the target domain, give it a list of elements in the source domain, and it returns a list in the target domain.

of course, neither of these do in-place updating of the list, they return the new list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜