Skip to content

Commit 2045f67

Browse files
committed
Add f-string docs
1 parent c2a226a commit 2045f67

File tree

12 files changed

+77
-72
lines changed

12 files changed

+77
-72
lines changed

docs/guide/ai/agent.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ agent CustomerSupport {
281281

282282
fn summarize_conversation() -> str {
283283
let history = conversation_history.join("\n");
284-
return prompt "Summarize this conversation: {history}";
284+
return prompt f"Summarize this conversation: {history}";
285285
}
286286
}
287287
```
@@ -296,7 +296,7 @@ agent CodeExpert {
296296
model: "gpt-4", // More capable model for coding tasks
297297

298298
fn review_code(code: str) -> str {
299-
return prompt "Review this code and provide feedback: {code}";
299+
return prompt f"Review this code and provide feedback: {code}";
300300
}
301301
}
302302

docs/guide/ai/function.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ You can not use `prompt` outside the non-ai function.
2121
```rust
2222
fn analyze_sentiment(text: str) -> float {
2323
// [line 3] Error at 'prompt': Can't prompt outside of ai function or root script.
24-
let sentiment = prompt "Analyze the sentiment of this text and return a score between -1 and 1: {text}";
24+
let sentiment = prompt f"Analyze the sentiment of this text and return a score between -1 and 1: {text}";
2525
return float(sentiment);
2626
}
2727
```
@@ -34,7 +34,7 @@ Here's a basic example of an AI function that analyzes sentiment in text:
3434

3535
```rust
3636
ai fn analyze_sentiment(text: str) -> float {
37-
let sentiment = prompt "Analyze the sentiment of this text and return a score between -1 and 1: {text}";
37+
let sentiment = prompt f"Analyze the sentiment of this text and return a score between -1 and 1: {text}";
3838
return float(sentiment);
3939
}
4040

@@ -50,14 +50,14 @@ Since AI functions often involve network operations and third-party services, it
5050

5151
```rust
5252
ai fn generate_summary(text: str) -> str | NetworkError! {
53-
let summary = prompt "Summarize this text in 2-3 sentences: {text}" ?;
53+
let summary = prompt f"Summarize this text in 2-3 sentences: {text}" ?;
5454
return summary;
5555
}
5656

5757
// Using the function with error handling
5858
let article = "...long article text...";
5959
let summary = generate_summary(article) |err| {
60-
print("Failed to generate summary: {err}");
60+
print(f"Failed to generate summary: {err}");
6161
return "Summary unavailable";
6262
};
6363
```
@@ -69,7 +69,7 @@ You can customize the behavior of AI functions by configuring prompt parameters:
6969
```rust
7070
ai fn generate_ideas(topic: str, count: int = 3) -> str {
7171
let ideas = prompt {
72-
input: "Generate {count} creative ideas about {topic}",
72+
input: f"Generate {count} creative ideas about {topic}",
7373
temperature: 0.9, // Higher creativity
7474
max_tokens: 300
7575
};

docs/guide/ai/prompt.mdx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ Like other AIScript operations, you can use error handling with the `prompt` key
8888

8989
```rust
9090
let response = prompt "Generate a complex response" |err| {
91-
print("Error occurred: {err}");
91+
print(f"Error occurred: {err}");
9292
return "Fallback response";
9393
};
9494
```
@@ -126,13 +126,13 @@ print(poem);
126126
```rust
127127
// Using OpenAI
128128
let openai_response = prompt {
129-
input: "Summarize this article: {article_text}",
129+
input: f"Summarize this article: {article_text}",
130130
model: "gpt-4"
131131
};
132132

133133
// Using Claude
134134
let claude_response = prompt {
135-
input: "Summarize this article: {article_text}" ,
135+
input: f"Summarize this article: {article_text}" ,
136136
model: "claude-3.7"
137137
};
138138
```
@@ -141,8 +141,8 @@ let claude_response = prompt {
141141

142142
```rust
143143
let topic = prompt "Suggest a topic for a blog post";
144-
let outline = prompt "Create an outline for a blog post about: {topic}";
145-
let introduction = prompt "Write an introduction for a blog post with this outline: {outline}";
144+
let outline = prompt f"Create an outline for a blog post about: {topic}";
145+
let introduction = prompt f"Write an introduction for a blog post with this outline: {outline}";
146146

147147
print("Topic:", topic);
148148
print("Outline", outline);

docs/guide/contribution/roadmap.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@ Currently, **AIScript** is in its early stages of development. This roadmap outl
44

55
## Language Features
66

7-
- [ ] **String Interpolation Enhancement**
7+
- [x] **String Interpolation**
88
- Improve the current string interpolation with formatting options
99
- Add support for more complex expressions within interpolated strings
1010

11+
- [ ] `for in` Loop
12+
- Add support for iterating over arrays and objects
13+
1114
- [ ] **Type System Improvements**
1215
- Enhance type annotations and static checking
1316

docs/guide/language/basic.mdx

Lines changed: 40 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Badge } from 'rspress/theme';
1+
import { Badge } from "rspress/theme";
22

33
# Basic Syntax
44

@@ -56,7 +56,6 @@ if len(global_variable) > 1 {
5656

5757
Constants are declared with the `const` keyword and are immutable. Constants can only be declared once and must be initialized with a value; they cannot be reassigned.
5858

59-
6059
```js
6160
const PI = 3.14;
6261

@@ -94,17 +93,18 @@ let numbers = [1, 2, 3, 4, 5];
9493
// object literal
9594
let address_key = "address";
9695
let person = {
97-
"name": "AIScript",
98-
age: 18, // double quotes are optional
99-
"is_male": true,
100-
"hobbies": ["reading", "coding", "gaming"],
101-
[address_key]: { // key name are computable
102-
"city": "Beijing",
103-
"street": "No. 100, Xihuan Road",
104-
"zipcode": "100000",
105-
"country": "China",
106-
"phone": "13800138000",
107-
}
96+
name: "AIScript",
97+
age: 18, // double quotes are optional
98+
is_male: true,
99+
hobbies: ["reading", "coding", "gaming"],
100+
[address_key]: {
101+
// key name are computable
102+
city: "Beijing",
103+
street: "No. 100, Xihuan Road",
104+
zipcode: "100000",
105+
country: "China",
106+
phone: "13800138000",
107+
},
108108
};
109109

110110
// tuples
@@ -167,13 +167,37 @@ let b = "Hello, {a}!";
167167

168168
// string concatenation
169169
let a = "AIScript";
170-
let b = "Hello, " + a + "!";
170+
let b = "Hello, {a}!";
171171

172172
// string length
173173
let a = "AIScript";
174174
print(len(a)); // print 8
175175
```
176176

177+
## Formatted String Literal
178+
179+
AIScript supports `f-strings` (formatted string literals, like Python's [f-string](https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings) but not identical) for string interpolation. F-strings provide a concise and readable way to embed expressions inside string literals. To create an f-string, prefix the string with `f` and use curly braces `{}` to include expressions.
180+
181+
```js
182+
let name = "Alice";
183+
let greeting = f"Hello, {name}!";
184+
print(greeting); // Hello, Alice!
185+
186+
let x = 10;
187+
let y = 5;
188+
print(f"{x} + {y} = {x + y}"); // 10 + 5 = 15
189+
print(f"{x} - {y} = {x - y}"); // 10 - 5 = 5
190+
print(f"{x} * {y} = {x * y}"); // 10 * 5 = 50
191+
print(f"{x} / {y} = {x / y}"); // 10 / 5 = 2
192+
```
193+
194+
F-strings can contain any valid AIScript expression inside the curly braces. The expressions are evaluated at runtime and their results are converted to strings. This makes f-strings particularly useful for:
195+
196+
- String interpolation with variables
197+
- Embedding arithmetic expressions
198+
- Calling functions within strings
199+
- Formatting complex data structures
200+
177201
## Control flow
178202

179203
```js
@@ -270,7 +294,6 @@ let d = a[:2]; // "AI"
270294

271295
```
272296

273-
274297
## Loops
275298

276299
AIScript only has two keyword for loops: `for` and `while`.
@@ -320,7 +343,7 @@ let person = {
320343
};
321344

322345
for (key, value) in person {
323-
print("{key}: {value}");
346+
print(f"{key}: {value}");
324347
}
325348
```
326349

@@ -332,7 +355,6 @@ for i in 1..10 {
332355
}
333356
```
334357

335-
336358
### Break and Continue
337359

338360
```js
@@ -359,4 +381,4 @@ AIScript provide a convenient way to access environment variables, the syntax is
359381
```rust
360382
let home = $HOME;
361383
print(home);
362-
```
384+
```

docs/guide/language/closure-lambda.md

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -104,26 +104,6 @@ print(math.multiply(5)); // 10
104104
print(math.combined(5)); // 30
105105
``` -->
106106

107-
<!-- ## Partial Application
108-
109-
Use closures to create partially applied functions:
110-
111-
```js
112-
fn partial(func, ...fixed_args) -> fn {
113-
return |...args| func(...fixed_args, ...args);
114-
}
115-
116-
fn greet(greeting, name) -> str {
117-
return "{greeting}, {name}!";
118-
}
119-
120-
let hello = partial(greet, "Hello");
121-
let goodbye = partial(greet, "Goodbye");
122-
123-
print(hello("Alice")); // "Hello, Alice!"
124-
print(goodbye("Bob")); // "Goodbye, Bob!"
125-
``` -->
126-
127107
## Immediate Invocation
128108

129109
You can immediately invoke a lambda after defining it:
@@ -166,9 +146,9 @@ Closures are ideal for event-driven or asynchronous programming:
166146
fn fetch_data(url: str, on_success, on_error) {
167147
// Simulating an async operation
168148
if url.starts_with("https") {
169-
on_success("Data from {url}");
149+
on_success(f"Data from {url}");
170150
} else {
171-
on_error("Invalid URL: {url}");
151+
on_error(f"Invalid URL: {url}");
172152
}
173153
}
174154

docs/guide/language/enum-match.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,9 @@ let point = [10, 20];
196196

197197
match point {
198198
[0, 0] => print("At origin"),
199-
[0, y] => print("On y-axis at y={y}"),
200-
[x, 0] => print("On x-axis at x={x}"),
201-
[x, y] => print("At position ({x}, {y})"),
199+
[0, y] => print(f"On y-axis at y={y}"),
200+
[x, 0] => print(f"On x-axis at x={x}"),
201+
[x, y] => print(f"At position ({x}, {y})"),
202202
};
203203
```
204204

@@ -213,7 +213,7 @@ match num {
213213
n if n % 15 == 0 => print("FizzBuzz"),
214214
n if n % 3 == 0 => print("Fizz"),
215215
n if n % 5 == 0 => print("Buzz"),
216-
n => print("{n}"),
216+
n => print(f"{n}"),
217217
};
218218
```
219219

docs/guide/web/database.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ let tx = pg.begin_transaction();
7373

7474
// Execute multiple operations within the transaction
7575
tx.query("INSERT INTO users (name, email) VALUES($1, $2);", "Alice", "[email protected]") |err| {
76-
print("Transaction failed: {err}");
76+
print(f"Transaction failed: {err}");
7777
tx.rollback();
7878
return;
7979
};
8080
tx.query("INSERT INTO user_roles (user_id, role) VALUES(LASTVAL(), 'admin');") |err| {
81-
print("Transaction failed: {err}");
81+
print(f"Transaction failed: {err}");
8282
tx.rollback();
8383
return;
8484
};
@@ -132,12 +132,12 @@ use std.db.sqlite;
132132
let tx = sqlite.begin_transaction();
133133

134134
tx.query("INSERT INTO notes (title, content) VALUES($1, $2);", "Note 1", "Content 1") |err| {
135-
print("Transaction failed: {err}");
135+
print(f"Transaction failed: {err}");
136136
tx.rollback();
137137
return;
138138
};
139139
tx.query("INSERT INTO notes (title, content) VALUES($1, $2);", "Note 2", "Content 2") |err| {
140-
print("Transaction failed: {err}");
140+
print(f"Transaction failed: {err}");
141141
tx.rollback();
142142
return;
143143
};

docs/guide/web/openapi-docs.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ post /api/chat {
1919
message: str,
2020
}
2121

22-
return "Input: " + body.message + "!";
22+
return f"Input: {body.message}!";
2323
}
2424
```
2525

docs/guide/web/route.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ get /hello {
5454
name: str = "Alice"
5555
}
5656

57-
return "Hello, " + query.name + "!";
57+
return f"Hello, {query.name}!";
5858
}
5959
```
6060

@@ -93,7 +93,7 @@ post /hello {
9393
name: str
9494
}
9595

96-
return "Hello, " + body.name + "!";
96+
return f"Hello, {body.name}!";
9797
}
9898
```
9999

@@ -113,7 +113,7 @@ post /hello {
113113
name: str
114114
}
115115

116-
return "Hello, " + body.name + "!";
116+
return f"Hello, {body.name}!";
117117
}
118118
```
119119

@@ -136,7 +136,7 @@ get /hello {
136136
header.test = "Test Header";
137137
// Modify cookie
138138
cookie.xyz = "changed";
139-
return "header: abc={abc}, cookie: xyz={xyz}";
139+
return f"header: abc={abc}, cookie: xyz={xyz}";
140140
}
141141
```
142142

@@ -150,7 +150,7 @@ get /hello {
150150
let scheme = request.scheme;
151151
let host = request.host;
152152
let port = request.port;
153-
return "method: {method}, url: {url}, path: {path}, scheme: {scheme}, host: {host}, port: {port}";
153+
return f"method: {method}, url: {url}, path: {path}, scheme: {scheme}, host: {host}, port: {port}";
154154
}
155155
```
156156

docs/reference/route/keyword.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ get /search {
128128

129129
let term = query.term;
130130
let page = query.page;
131-
return "Searching for '{term}' on page {page}";
131+
return f"Searching for '{term}' on page {page}";
132132
}
133133
```
134134

@@ -145,7 +145,7 @@ get /users/:id/posts/:postId {
145145

146146
let userId = path.id;
147147
let postId = path.postId;
148-
return "Accessing post {postId} for user {userId}";
148+
return f"Accessing post {postId} for user {userId}";
149149
}
150150
```
151151

@@ -175,7 +175,7 @@ Access request headers through the `header` object.
175175
get /headers {
176176
let userAgent = header["User-Agent"];
177177
let contentType = header["Content-Type"];
178-
return "User-Agent: {userAgent}, Content-Type: {contentType}";
178+
return f"User-Agent: {userAgent}, Content-Type: {contentType}";
179179
}
180180
```
181181

0 commit comments

Comments
 (0)