views:

153

answers:

1

Possible Duplicate:
How to convert this C# code to Objective-C

This code purportedly does what I need in Objective-C but it's written in a different language. So I'm trying to convert this code to objective-c but I need to understand it better. It would be easier to understand if it was in pseudocode

static public IEnumerable<string> permute(string word)
{
    if (word.Length > 1)
    {

        char character = word[0];
        foreach (string subPermute in permute(word.Substring(1)))
        {

            for (int index = 0; index <= subPermute.Length; index++)
            {
                string pre = subPermute.Substring(0, index);
                string post = subPermute.Substring(index);

                if (post.Contains(character))
                        continue;                       

                yield return pre + character + post;
            }

        }
    }
    else
    {
        yield return word;
    }
}
+7  A: 

Basically, it's an iterator-generator. This means it's actually a state machine not a function or method. When you call it, it returns a IEnumerable. This is a C# type used for anything (lists, sets, arrays) you might want to iterate/enumerate over. The caller can iterate over that with a for-each loop to get each value.

Every time you see yield return a value is being added to the generator. When the "function" ends, the generator is exhausted.

Generators use deferred execution. Thus means no actual work is done until someone calls MoveNext on the returned value. The state machine freezes after each yield return until MoveNext is called again.

This may not be intuitive at first, so you should find a good tutorial on C# generators.

EDIT: Okay, here's an attempt at custom psuedo-code.

generator<string> permute(word : string)
    if (length(word) > 1)
        character := word[0]
        for subPermute in permute(word[1,])
            for i in 0..subPermute.Length
                pre := subPermute[0, index]
                post := subPermute[index,]
                if post.contains(character)
                    start next inner for                         
                yield pre + character + post
    else
        yield word
Matthew Flaschen
I know what the code does I just need it all in pseudocode so I can convert it.
awakeFromNib
Cool, so what does yield do? Is that in objective-c?
awakeFromNib
@awake, I tried to explain that before. It basically marks a place in the state machine where a value is being provided. As stated in an answer to the [other question](http://stackoverflow.com/questions/3791843/how-to-convert-this-c-code-to-objective-c), I don't think Obj-C has that.
Matthew Flaschen
With the block `^(){...}` , you can make a state machine :) There was a blog post, if I remember correctly. So Obj-C has it.
Yuji