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
//! The string editing domain, for tackling Flashfill-style problems.
//!
//! # Examples
//!
//! ```
//! #[macro_use]
//! extern crate polytype;
//! extern crate programinduction;
//! use programinduction::{lambda, ECParams, EC};
//! use programinduction::domains::strings;
//!
//! # fn main() {
//! let dsl = strings::dsl();
//! let examples = vec![
//!     // Replace delimiter '>' with '/'
//!     (
//!         vec![strings::Space::Str("OFJQc>BLVP>eMS".to_string())],
//!         strings::Space::Str("OFJQc/BLVP/eMS".to_string()),
//!     ),
//! ];
//! let task = lambda::task_by_evaluation(
//!     strings::Evaluator,
//!     ptp!(@arrow[tp!(str), tp!(str)]),
//!     &examples,
//! );
//!
//! let ec_params = ECParams {
//!     frontier_limit: 10,
//!     search_limit_timeout: None,
//!     search_limit_description_length: Some(12.0),
//! };
//! let frontiers = dsl.explore(&ec_params, &[task]);
//! let solution = &frontiers[0].best_solution().unwrap().0;
//! assert_eq!(
//!     "(λ (join (char->str /) (split > $0)))",
//!     dsl.display(solution)
//! );
//! # }
//! ```

use itertools::Itertools;

use lambda::{Evaluator as EvaluatorT, Language, LiftedFunction};

/// The string editing [`lambda::Language`] defines the following operations:
///
/// ```ignore
/// "0":         ptp!(int)
/// "+1":        ptp!(@arrow[tp!(int), tp!(int)])
/// "-1":        ptp!(@arrow[tp!(int), tp!(int)])
/// "len":       ptp!(@arrow[tp!(str), tp!(int)])
/// "empty_str": ptp!(str)
/// "lower":     ptp!(@arrow[tp!(str), tp!(str)])
/// "upper":     ptp!(@arrow[tp!(str), tp!(str)])
/// "concat":    ptp!(@arrow[tp!(str), tp!(str), tp!(str)])
/// "slice":     ptp!(@arrow[tp!(int), tp!(int), tp!(str), tp!(str)])
/// "nth":       ptp!(@arrow[tp!(int), tp!(list(tp!(str))), tp!(str)])
/// "map":       ptp!(0, 1; @arrow[
///                  tp!(@arrow[tp!(0), tp!(1)]),
///                  tp!(list(tp!(0))),
///                  tp!(list(tp!(1))),
///              ])
/// "strip":     ptp!(@arrow[tp!(str), tp!(str)])
/// "split":     ptp!(@arrow[tp!(char), tp!(str), tp!(list(tp!(str)))])
/// "join":      ptp!(@arrow[tp!(str), tp!(list(tp!(str))), tp!(str)])
/// "char->str": ptp!(@arrow[tp!(char), tp!(str)])
/// "space":     ptp!(char)
/// ".":         ptp!(char)
/// ",":         ptp!(char)
/// "<":         ptp!(char)
/// ">":         ptp!(char)
/// "/":         ptp!(char)
/// "@":         ptp!(char)
/// "-":         ptp!(char)
/// "|":         ptp!(char)
/// ```
///
/// [`lambda::Language`]: ../../lambda/struct.Language.html
pub fn dsl() -> Language {
    Language::uniform(vec![
        ("0", ptp!(int)),
        ("+1", ptp!(@arrow[tp!(int), tp!(int)])),
        ("-1", ptp!(@arrow[tp!(int), tp!(int)])),
        ("len", ptp!(@arrow[tp!(str), tp!(int)])),
        ("empty_str", ptp!(str)),
        ("lower", ptp!(@arrow[tp!(str), tp!(str)])),
        ("upper", ptp!(@arrow[tp!(str), tp!(str)])),
        ("concat", ptp!(@arrow[tp!(str), tp!(str), tp!(str)])),
        (
            "slice",
            ptp!(@arrow[tp!(int), tp!(int), tp!(str), tp!(str)]),
        ),
        ("nth", ptp!(@arrow[tp!(int), tp!(list(tp!(str))), tp!(str)])),
        (
            "map",
            ptp!(0, 1; @arrow[tp!(@arrow[tp!(0), tp!(1)]), tp!(list(tp!(0))), tp!(list(tp!(1)))]),
        ),
        ("strip", ptp!(@arrow[tp!(str), tp!(str)])),
        (
            "split",
            ptp!(@arrow[tp!(char), tp!(str), tp!(list(tp!(str)))]),
        ),
        (
            "join",
            ptp!(@arrow[tp!(str), tp!(list(tp!(str))), tp!(str)]),
        ),
        ("char->str", ptp!(@arrow[tp!(char), tp!(str)])),
        ("space", ptp!(char)),
        (".", ptp!(char)),
        (",", ptp!(char)),
        ("<", ptp!(char)),
        (">", ptp!(char)),
        ("/", ptp!(char)),
        ("@", ptp!(char)),
        ("-", ptp!(char)),
        ("|", ptp!(char)),
    ])
}

use self::Space::*;
/// All values in the strings domain can be represented in this `Space`.
#[derive(Clone)]
pub enum Space {
    Num(i32),
    Char(char),
    Str(String),
    StrList(Vec<String>),
    NumList(Vec<i32>),
    Func(LiftedFunction<Space, Evaluator>),
}
impl PartialEq for Space {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (&Num(x), &Num(y)) => x == y,
            (&Char(x), &Char(y)) => x == y,
            (&Str(ref x), &Str(ref y)) => x == y,
            (&StrList(ref xs), &StrList(ref ys)) => xs == ys,
            (&NumList(ref xs), &NumList(ref ys)) => xs == ys,
            _ => false,
        }
    }
}
/// An [`Evaluator`] for the strings domain.
///
/// [`Evaluator`]: ../../lambda/trait.Evaluator.html
#[derive(Copy, Clone)]
pub struct Evaluator;
impl EvaluatorT for Evaluator {
    type Space = Space;
    fn evaluate(&self, name: &str, inps: &[Self::Space]) -> Self::Space {
        match OPERATIONS[name] {
            Op::Zero => Num(0),
            Op::Incr => match inps[0] {
                Num(x) => Num(x + 1),
                _ => unreachable!(),
            },
            Op::Decr => match inps[0] {
                Num(x) => Num(x - 1),
                _ => unreachable!(),
            },
            Op::Len => match inps[0] {
                Str(ref s) => Num(s.len() as i32),
                _ => unreachable!(),
            },
            Op::Empty => Str(String::new()),
            Op::Lower => match inps[0] {
                Str(ref s) => Str(s.to_lowercase()),
                _ => unreachable!(),
            },
            Op::Upper => match inps[0] {
                Str(ref s) => Str(s.to_uppercase()),
                _ => unreachable!(),
            },
            Op::Concat => match (&inps[0], &inps[1]) {
                (&Str(ref x), &Str(ref y)) => {
                    let mut s = x.to_string();
                    s.push_str(y);
                    Str(s)
                }
                _ => unreachable!(),
            },
            Op::Slice => match (&inps[0], &inps[1], &inps[2]) {
                (&Num(x), &Num(y), &Str(ref s)) => {
                    Str(s.chars().skip(x as usize).take((y - x) as usize).collect())
                }
                _ => unreachable!(),
            },
            Op::Nth => match (&inps[0], &inps[1]) {
                (&Num(x), &StrList(ref ss)) => {
                    Str(ss.get(x as usize).cloned().unwrap_or_else(String::new))
                }
                _ => unreachable!(),
            },
            Op::Map => match (&inps[0], &inps[1]) {
                (&Func(ref f), &NumList(ref xs)) => NumList(
                    xs.into_iter()
                        .cloned()
                        .map(|x| match f.eval(&[Num(x)]) {
                            Num(y) => y,
                            _ => panic!("map given invalid function"),
                        })
                        .collect(),
                ),
                (&Func(ref f), &StrList(ref xs)) => StrList(
                    xs.into_iter()
                        .cloned()
                        .map(|x| match f.eval(&[Str(x)]) {
                            Str(y) => y,
                            _ => panic!("map given invalid function"),
                        })
                        .collect(),
                ),
                _ => unreachable!(),
            },
            Op::Strip => match inps[0] {
                Str(ref s) => Str(s.trim().to_string()),
                _ => unreachable!(),
            },
            Op::Split => match (&inps[0], &inps[1]) {
                (&Char(c), &Str(ref s)) => StrList(s.split(c).map(str::to_string).collect()),
                _ => unreachable!(),
            },
            Op::Join => match (&inps[0], &inps[1]) {
                (&Str(ref delim), &StrList(ref ss)) => Str(ss.iter().join(delim)),
                _ => unreachable!(),
            },
            Op::CharToStr => match inps[0] {
                Char(c) => Str(c.to_string()),
                _ => unreachable!(),
            },
            Op::CharSpace => Char(' '),
            Op::CharDot => Char('.'),
            Op::CharComma => Char(','),
            Op::CharLess => Char('<'),
            Op::CharGreater => Char('>'),
            Op::CharSlash => Char('/'),
            Op::CharAt => Char('@'),
            Op::CharDash => Char('-'),
            Op::CharPipe => Char('|'),
        }
    }
    fn lift(&self, f: LiftedFunction<Self::Space, Self>) -> Result<Self::Space, ()> {
        Ok(Func(f))
    }
}

/// Using an enum with a hashmap will be much faster than string comparisons.
enum Op {
    Zero,
    Incr,
    Decr,
    Len,
    Empty,
    Lower,
    Upper,
    Concat,
    Slice,
    Nth,
    Map,
    Strip,
    Split,
    Join,
    CharToStr,
    CharSpace,
    CharDot,
    CharComma,
    CharLess,
    CharGreater,
    CharSlash,
    CharAt,
    CharDash,
    CharPipe,
}

lazy_static! {
    static ref OPERATIONS: ::std::collections::HashMap<&'static str, Op> =
        hashmap!{
            "0" => Op::Zero,
            "+1" => Op::Incr,
            "-1" => Op::Decr,
            "len" => Op::Len,
            "empty_str" => Op::Empty,
            "lower" => Op::Lower,
            "upper" => Op::Upper,
            "concat" => Op::Concat,
            "slice" => Op::Slice,
            "nth" => Op::Nth,
            "map" => Op::Map,
            "strip" => Op::Strip,
            "split" => Op::Split,
            "join" => Op::Join,
            "char->str" => Op::CharToStr,
            "space" => Op::CharSpace,
            "." => Op::CharDot,
            "," => Op::CharComma,
            "<" => Op::CharLess,
            ">" => Op::CharGreater,
            "/" => Op::CharSlash,
            "@" => Op::CharAt,
            "-" => Op::CharDash,
            "|" => Op::CharPipe,
        };
}