tags:

views:

55

answers:

2

How to declare a function suffixsen : string list -> string list ???

Tnx.

+2  A: 

The syntax to define a function with one argument in sml is:

fun functionName argumentName = functionBody

or

fun functionName (argumentName : argumentType) = functionBody

if you want to specify the type explicitly. So to define a function named suffixsen of type string list -> string list, you can do:

fun suffixsen (strings : string list) = someExpressionThatReturnsAStringList

Edit in response to you comment:

In order to append "son" to each string in the list, you should look at the ^ operator[1], which concatenates string, and the map function which performs an operation for each element in a list.

[1] http://www.standardml.org/Basis/string.html#SIG:STRING.^:VAL (copy and paste this link in your browser - for some reason I can't get this to be clickable)

sepp2k
I don't really get it, because I have to make a list like so it adds "son" Like:suffixsen ["Tom", "Peter", "John"] should return:["Tomson", "Peterson", "Johnson"].
peter81
@master09: Since you did not mention what the function is supposed to do in your question, I could not possibly have incorporated that into my answer.
sepp2k
@master: I've edited my answer.
sepp2k
yees I see, but what does it mean: map f s applies f to each element of s from left to right, returning the resulting string. It is equivalent to implode(List.map f (explode s)).
peter81
@master: I was talking about (and linked to) `List.map` (aka just `map`), not `String.map`. You want to perform an operation for each string in the string list, namely: appending "son" (using `^`). So you need to use `List.map`.
sepp2k
@master: Yes, except `+` is for adding integers, not concatenating strings. So it needs to be `x ^ "son"` instead of `x + "son"`. Which is exactly what I meant with "using ^".
sepp2k
@master: Ah, yes, it needs to be `fun suffixsen strings = map (fn x => x^"sen") strings` or `val suffixsen = map (fn x => x^"sen")`. If you use `fun` you need to define the function with an argument.
sepp2k
@master: Yes, add another argument: `fun suffixgen suffix strings = map ...`
sepp2k
ja okay... now I get it :D thank you so much dude.. by the way, why does my test return false? fun suffixsen strings = map (fn x => x^"sen") strings val testsuffixsen1 = ["Anders", "Peter", "Johan"] = ["Anderssen", "Petersen", "Johansen"] ??
peter81
@master: Because you're not calling your `suffixsen` function. It needs to be `suffixsen ["Anders", "Peter", "Johan"] = ["Anderssen", "Petersen", "Johansen"]`
sepp2k
A: 

After declaring types inside the parens, declare the function's return type on the outside with :return-type. At leat in SMLnj. I found this through trial and error, can't find documentation for it.

fun suffixson (xs: string list ): string list =
    map (fn x => x ^ "son") xs
Frayser