Skip to content

Commit

Permalink
Improve the higher order function example after feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
dfellis committed Aug 19, 2024
1 parent 40ca13d commit 09422aa
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -670,34 +670,40 @@ You can create functions that accept other functions as an argument and then cal
Just the type portion of the function definition needs to be provided.

```rs
fn foostring (s: string) -> string = "foo".concat(s);
// "Doubles" the string by concatenating it to itself
fn doublestring(s: string) -> string = s.concat(s);

// Accepts a function that transforms a string and then returns a
// string that documents that change
fn stringChanger(s: string, changer: (string) -> string) -> string {
"Original String: ".concat(s).print;
let out = changer(s);
"New String : ".concat(out).print;
return out;
return s.concat(" becomes ").concat(changer(s));
}

export fn main {
let changed = stringChanger("bar", foostring);
"New Length : ".concat(changed.len.string).print;
stringChanger("baz", fn (s: string) -> string = changed.concat(s)).print;
// Calling `doublestring`
let danceName = doublestring("can");
// Call `stringChanger` with a string and the `doublestring` function
stringChanger("can", doublestring).print;
// Call `stringChanger` with a string and a closure function that
// encloses the `danceName` variable defined above
stringChanger(
"a person",
fn (s: string) -> string = s
.concat(" who can dance the ")
.concat(danceName)
.concat(" through practice")
).print;
}
```

We can now pass in the `foostring` function as well as an anonymous closure function that uses the `changed` variable itself to produce a new output. The full output of this example when compiled and run looks like:

```
$ alan compile changer.ln
Done! Took 0.73sec
Done! Took 0.67sec
$ ./changer
Original String: bar
New String : foobar
New Length : 6
Original String: baz
New String : foobarbaz
foobarbaz
can becomes cancan
a person becomes a person who can dance the cancan through practice
```

The same `stringChanger` function produced different outputs based on the behavior of the function it was provided.
Expand Down

0 comments on commit 09422aa

Please sign in to comment.