stillwater 1.0.1

Pragmatic effect composition and validation for Rust - pure core, imperative shell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Effects Example
//!
//! Demonstrates the Effect type and composition patterns using the free function style.
//! Shows practical patterns including:
//! - Creating effects with free functions (pure, fail, from_fn, from_async)
//! - Mapping and transforming effects
//! - Chaining effects with and_then
//! - Error handling with map_err
//! - Helper combinators (tap, check, with)
//! - Combining independent effects with zip
//! - Environment-based dependency injection
//!
//! All examples use the prelude import for concise, ergonomic effect creation.

use stillwater::effect::prelude::*;

// ==================== Basic Effects ====================

/// Example 1: Creating basic effects
///
/// Demonstrates pure() and fail() constructors.
async fn example_basic_effects() {
    println!("\n=== Example 1: Basic Effects ===");

    // Pure value - always succeeds
    let success_effect = pure::<_, String, ()>(42);
    let result = success_effect.execute(&()).await;
    println!("Pure effect: {:?}", result);

    // Failure - always fails
    let fail_effect = fail::<i32, _, ()>("something went wrong".to_string());
    let result = fail_effect.execute(&()).await;
    println!("Fail effect: {:?}", result);
}

// ==================== Creating Effects from Functions ====================

/// Example 2: Effects from synchronous functions
///
/// Demonstrates using from_fn() to create effects from pure functions.
async fn example_from_fn() {
    println!("\n=== Example 2: Effects from Functions ===");

    // Simple environment
    #[derive(Clone)]
    struct Env {
        multiplier: i32,
    }

    // Effect from a function that uses the environment
    let effect = from_fn(|env: &Env| Ok::<_, String>(env.multiplier * 2));

    let env = Env { multiplier: 21 };
    let result = effect.execute(&env).await;
    println!("Result: {:?}", result);
}

// ==================== Mapping Effects ====================

/// Example 3: Transforming values with map
///
/// Demonstrates using map() to transform successful values.
async fn example_mapping() {
    println!("\n=== Example 3: Mapping Effects ===");

    #[derive(Clone)]
    struct Env {
        base_value: i32,
    }

    // Chain multiple transformations
    let effect = from_fn(|env: &Env| Ok::<_, String>(env.base_value))
        .map(|x| x * 2) // Double it
        .map(|x| x + 10) // Add 10
        .map(|x| format!("Result: {}", x)); // Convert to string

    let env = Env { base_value: 5 };
    let result = effect.execute(&env).await.unwrap();
    println!("{}", result); // "Result: 20"
}

// ==================== Chaining Effects ====================

/// Example 4: Chaining effects with and_then
///
/// Demonstrates using and_then() to sequence effects that depend on previous results.
async fn example_chaining() {
    println!("\n=== Example 4: Chaining Effects ===");

    #[derive(Clone)]
    struct Database {
        value: i32,
    }

    #[derive(Clone)]
    struct Env {
        db: Database,
    }

    impl AsRef<Database> for Env {
        fn as_ref(&self) -> &Database {
            &self.db
        }
    }

    // First effect: get value from database
    fn get_value() -> impl Effect<Output = i32, Error = String, Env = Env> {
        from_fn(|env: &Env| Ok::<_, String>(env.db.value))
    }

    // Second effect: validate and double the value
    fn validate_and_double(x: i32) -> impl Effect<Output = i32, Error = String, Env = Env> {
        from_fn(move |_: &Env| {
            if x > 0 {
                Ok(x * 2)
            } else {
                Err("Value must be positive".to_string())
            }
        })
    }

    let env = Env {
        db: Database { value: 10 },
    };
    let result = get_value()
        .and_then(validate_and_double)
        .execute(&env)
        .await;
    println!("Success case: {:?}", result);

    // Try with negative value
    let env2 = Env {
        db: Database { value: -5 },
    };
    let result2 = get_value()
        .and_then(validate_and_double)
        .execute(&env2)
        .await;
    println!("Failure case: {:?}", result2);
}

// ==================== Error Handling ====================

/// Example 5: Handling errors with map_err
///
/// Demonstrates using map_err() to transform error values.
async fn example_error_handling() {
    println!("\n=== Example 5: Error Handling ===");

    #[derive(Clone)]
    struct Env {
        value: i32,
    }

    // Effect that might fail
    let _effect = from_fn(|env: &Env| {
        if env.value > 0 {
            Ok::<_, &str>(env.value)
        } else {
            Err("negative")
        }
    })
    .map_err(|e| format!("Error: {} is not allowed", e));

    let env1 = Env { value: 42 };
    let effect1 = from_fn(|env: &Env| {
        if env.value > 0 {
            Ok::<_, &str>(env.value)
        } else {
            Err("negative")
        }
    })
    .map_err(|e| format!("Error: {} is not allowed", e));
    println!("Valid value: {:?}", effect1.execute(&env1).await);

    let env2 = Env { value: -1 };
    let effect2 = from_fn(|env: &Env| {
        if env.value > 0 {
            Ok::<_, &str>(env.value)
        } else {
            Err("negative")
        }
    })
    .map_err(|e| format!("Error: {} is not allowed", e));
    println!("Invalid value: {:?}", effect2.execute(&env2).await);
}

// ==================== Async Effects ====================

/// Example 6: Async effects
///
/// Demonstrates using from_async() for asynchronous operations.
async fn example_async_effects() {
    println!("\n=== Example 6: Async Effects ===");

    #[derive(Clone)]
    struct ApiClient {
        base_url: String,
    }

    #[derive(Clone)]
    struct Env {
        api: ApiClient,
    }

    impl AsRef<ApiClient> for Env {
        fn as_ref(&self) -> &ApiClient {
            &self.api
        }
    }

    let env = Env {
        api: ApiClient {
            base_url: "https://api.example.com".to_string(),
        },
    };

    // Async effect: simulate API call
    let fetch_user = from_async(|env: &Env| {
        let url = env.api.base_url.clone();
        async move {
            // Simulate async work
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            Ok::<_, String>(format!("User from {}", url))
        }
    });

    let result = fetch_user.execute(&env).await.unwrap();
    println!("Fetched: {}", result);
}

// ==================== Helper Combinators ====================

/// Example 7: Using tap for side effects
///
/// Demonstrates tap() to perform side effects while passing the value through.
async fn example_tap() {
    println!("\n=== Example 7: Using tap() ===");

    #[derive(Clone)]
    struct Env {
        value: i32,
    }

    let effect = from_fn(|env: &Env| Ok::<_, String>(env.value))
        .tap(|x| {
            println!("  [DEBUG] Got value: {}", x);
            pure::<(), String, Env>(())
        })
        .map(|x| x * 2)
        .tap(|x| {
            println!("  [DEBUG] After doubling: {}", x);
            pure::<(), String, Env>(())
        })
        .map(|x| x + 5);

    let env = Env { value: 10 };
    let result = effect.execute(&env).await.unwrap();
    println!("Final result: {}", result);
}

/// Example 8: Using check for conditional validation
///
/// Demonstrates check() to validate values with a predicate.
async fn example_check() {
    println!("\n=== Example 8: Using check() ===");

    #[derive(Clone)]
    struct Env {
        age: i32,
    }

    let env1 = Env { age: 25 };
    let result1 = from_fn(|env: &Env| Ok::<_, String>(env.age))
        .and_then(|age| {
            from_fn(move |_: &Env| {
                if age >= 18 {
                    Ok(age)
                } else {
                    Err(format!("Age {} is below minimum (18)", age))
                }
            })
        })
        .execute(&env1)
        .await;
    println!("Adult: {:?}", result1);

    let env2 = Env { age: 16 };
    let result2 = from_fn(|env: &Env| Ok::<_, String>(env.age))
        .and_then(|age| {
            from_fn(move |_: &Env| {
                if age >= 18 {
                    Ok(age)
                } else {
                    Err(format!("Age {} is below minimum (18)", age))
                }
            })
        })
        .execute(&env2)
        .await;
    println!("Minor: {:?}", result2);
}

/// Example 9: Using with to combine effects
///
/// Demonstrates with() to run effects in sequence and combine results.
async fn example_with() {
    println!("\n=== Example 9: Using with() ===");

    #[derive(Clone)]
    struct Config {
        width: i32,
        height: i32,
    }

    #[derive(Clone)]
    struct Env {
        config: Config,
    }

    impl AsRef<Config> for Env {
        fn as_ref(&self) -> &Config {
            &self.config
        }
    }

    // Get width and height as separate effects, then combine
    let area_effect = from_fn(|env: &Env| Ok::<_, String>(env.config.width))
        .with(|_w| from_fn(|env: &Env| Ok::<_, String>(env.config.height)))
        .map(|(w, h)| w * h);

    let env = Env {
        config: Config {
            width: 10,
            height: 5,
        },
    };

    let area = area_effect.execute(&env).await.unwrap();
    println!("Area: {}", area);
}

// ==================== Combining Independent Effects ====================

/// Example 10: Using zip for independent effects
///
/// Demonstrates zip(), zip_with(), and zip3() for combining independent effects.
/// Unlike and_then() which expresses sequential dependency, zip() expresses
/// that effects are independent and both results are needed.
async fn example_zip() {
    println!("\n=== Example 10: Using zip() ===");

    #[derive(Clone, Debug)]
    struct User {
        name: String,
    }

    #[derive(Clone, Debug)]
    struct Settings {
        theme: String,
    }

    #[derive(Clone)]
    struct Env {
        user_name: String,
        theme: String,
    }

    // Two independent effects - neither depends on the other
    fn fetch_user() -> impl Effect<Output = User, Error = String, Env = Env> {
        from_fn(|env: &Env| {
            Ok(User {
                name: env.user_name.clone(),
            })
        })
    }

    fn fetch_settings() -> impl Effect<Output = Settings, Error = String, Env = Env> {
        from_fn(|env: &Env| {
            Ok(Settings {
                theme: env.theme.clone(),
            })
        })
    }

    let env = Env {
        user_name: "Alice".to_string(),
        theme: "dark".to_string(),
    };

    // Basic zip: combine two effects into a tuple
    let result = fetch_user().zip(fetch_settings()).execute(&env).await;
    println!("Basic zip: {:?}", result);

    // zip_with: combine with a function directly (more efficient than zip + map)
    let greeting = fetch_user()
        .zip_with(fetch_settings(), |user, settings| {
            format!("Hello {}, your theme is {}", user.name, settings.theme)
        })
        .execute(&env)
        .await;
    println!("zip_with: {:?}", greeting);

    // Chain multiple zips (creates nested tuples)
    let chained = pure::<_, String, Env>(1)
        .zip(pure(2))
        .zip(pure(3))
        .map(|((a, b), c)| a + b + c)
        .execute(&env)
        .await;
    println!("Chained zips ((a, b), c): {:?}", chained);

    // zip3: flat tuple result (cleaner than chained zips)
    let flat = zip3(
        pure::<_, String, Env>(1),
        pure::<_, String, Env>(2),
        pure::<_, String, Env>(3),
    )
    .map(|(a, b, c)| a + b + c)
    .execute(&env)
    .await;
    println!("zip3 (a, b, c): {:?}", flat);

    // Error handling: fail-fast semantics
    let with_error = pure::<_, String, Env>(1)
        .zip(fail::<i32, _, Env>("second failed".to_string()))
        .execute(&env)
        .await;
    println!("With error: {:?}", with_error);
}

// ==================== Combining Multiple Effects ====================

/// Example 11: Real-world composition
///
/// Demonstrates combining multiple patterns into a realistic workflow.
async fn example_composition() {
    println!("\n=== Example 11: Real-world Composition ===");

    #[derive(Clone)]
    struct User {
        id: u64,
        name: String,
        age: i32,
    }

    #[derive(Clone)]
    struct Database {
        users: Vec<User>,
    }

    #[derive(Clone)]
    struct Env {
        db: Database,
    }

    impl AsRef<Database> for Env {
        fn as_ref(&self) -> &Database {
            &self.db
        }
    }

    // Find user by ID
    fn find_user(user_id: u64) -> impl Effect<Output = User, Error = String, Env = Env> {
        from_fn(move |env: &Env| {
            env.db
                .users
                .iter()
                .find(|u| u.id == user_id)
                .cloned()
                .ok_or_else(|| format!("User {} not found", user_id))
        })
    }

    // Validate user age
    fn validate_adult(user: User) -> impl Effect<Output = User, Error = String, Env = Env> {
        from_fn(move |_: &Env| {
            if user.age >= 18 {
                Ok(user.clone())
            } else {
                Err(format!("User {} is not an adult", user.name))
            }
        })
    }

    // Format greeting
    fn greet(user: User) -> impl Effect<Output = String, Error = String, Env = Env> {
        pure(format!("Hello, {}!", user.name))
    }

    // Compose the workflow
    let workflow = find_user(1)
        .tap(|u| {
            println!("  Found user: {}", u.name);
            pure::<(), String, Env>(())
        })
        .and_then(validate_adult)
        .tap(|u| {
            println!("  Validated user: {}", u.name);
            pure::<(), String, Env>(())
        })
        .and_then(greet);

    let env = Env {
        db: Database {
            users: vec![
                User {
                    id: 1,
                    name: "Alice".to_string(),
                    age: 25,
                },
                User {
                    id: 2,
                    name: "Bob".to_string(),
                    age: 16,
                },
            ],
        },
    };

    // Success case
    match workflow.execute(&env).await {
        Ok(greeting) => println!("Success: {}", greeting),
        Err(e) => println!("Error: {}", e),
    }

    // Try with minor
    let workflow2 = find_user(2).and_then(validate_adult).and_then(greet);
    match workflow2.execute(&env).await {
        Ok(greeting) => println!("Success: {}", greeting),
        Err(e) => println!("Error: {}", e),
    }
}

// ==================== Main ====================

#[tokio::main]
async fn main() {
    println!("Effects Examples");
    println!("================");

    example_basic_effects().await;
    example_from_fn().await;
    example_mapping().await;
    example_chaining().await;
    example_error_handling().await;
    example_async_effects().await;
    example_tap().await;
    example_check().await;
    example_with().await;
    example_zip().await;
    example_composition().await;

    println!("\n=== All examples completed successfully! ===");
}