Skip to main content

Choice

Struct Choice 

Source
pub struct Choice<O> { /* private fields */ }
Expand description

A question with one answer from a list of options.

Each option has a name, an optional description, and a value of the type O. The answer is a ChoiceAnswer, with the probability of each option, and it gives the values back. choice! makes a Choice that the compiler checks. The constructors make one from data. A Choice has 1 to 255 options, and each name is different.

§Examples

The smallest Choice has a list of names, and the answer gives a name back:

use system2::Choice;

let team = Choice::new(
    "Which team must answer the ticket?",
    ["billing", "engineering", "support"],
)?;

A description tells Jev what an option means:

let teams = [
    ("billing", "Payments, invoices, and refunds."),
    ("engineering", "Bugs and outages."),
];
let team = Choice::with_descriptions("Which team must answer the ticket?", teams)?;

An option can be a value of the caller. A closure gives its name, or its name and description, and the answer gives the value back:

struct Team {
    name: String,
    duties: String,
    email: String,
}

let teams = vec![Team {
    name: "billing".to_string(),
    duties: "Payments, invoices, and refunds.".to_string(),
    email: "[email protected]".to_string(),
}];
let by_name = Choice::with_values("Which team must answer?", &teams, |team| &team.name)?;
let described = Choice::with_values("Which team must answer?", &teams, |team| {
    (&team.name, &team.duties)
})?;

An enum that derives Options gives its variants as the options. Each doc comment is a description:

use system2::Options;

#[derive(Debug, Clone, Copy, PartialEq, Options)]
enum Team {
    /// Payments, invoices, and refunds.
    Billing,
    /// Bugs and outages.
    Engineering,
}

let instructions = "Which team must answer the ticket?".to_string();
let team = Choice::<Team>::of(instructions)?;

choice! takes the same forms, and the compiler checks them. A question with no variable can be a constant:

use system2::prelude::*;
use system2::Choice;

#[derive(Debug, Clone, Copy, PartialEq, Options)]
enum Team {
    /// Payments, invoices, and refunds.
    Billing,
    /// Bugs and outages.
    Engineering,
}

const TEAM: Choice<Team> = choice!("Which team must answer the ticket?", Team);
const LANGUAGE: Choice<&str> = choice!("Which language is the ticket in?", ["en", "de", "fr"]);
const NEXT: Choice<&str> = choice!("What is the next step?", {
    "reply": "Reply to the customer.",
    "escalate": "Give the ticket to an engineer.",
});

let team = TEAM.ask("The site is down.").await?;
if *team.most_likely() == Team::Engineering && team.confidence() > 0.8 { /* … */ }

Implementations§

Source§

impl<O> Choice<O>

Source

pub fn new( instructions: impl Serialize, items: impl IntoIterator<Item = O>, ) -> Result<Self, InvalidChoice>
where O: Display,

Makes a Choice with an option for each item. The Display of an item is its name.

The options have no descriptions. The answer gives the items back.

§Errors
Source

pub fn with_descriptions<D: Serialize>( instructions: impl Serialize, options: impl IntoIterator<Item = (O, D)>, ) -> Result<Self, InvalidChoice>
where O: Display,

Makes a Choice from (name, description) pairs. The Display of a name is the name.

The pairs can be owned or borrowed, such as a Vec, a &BTreeMap, or a &serde_json::Map. A description is any Serialize value. A description of () or None sends no description. The answer gives the name back.

§Errors
Source

pub fn with_values<L: Label>( instructions: impl Serialize, values: impl IntoIterator<Item = O>, label: impl FnMut(&O) -> L, ) -> Result<Self, InvalidChoice>

Makes a Choice from the values of the caller, and a closure that gives their labels.

The closure gives a Label: a name, or a name and a description. The values need no Clone, and the answer gives a value back.

§Errors
Source

pub fn of(instructions: impl Serialize) -> Result<Self, InvalidChoice>
where O: Options,

Makes a Choice from instructions that come from data, with the options of the type O.

It validates the options of O again, as Choice::with_values does.

§Errors

InvalidChoice::Instructions if the instructions do not serialize, are empty, or are a bare number or bool. The derive of Options validates the options, so another variant does not occur.

Source

pub const fn tag<T>(self, tag: T) -> Tagged<Self, T>

Puts a tag next to the question, so that the answer comes back next to it.

It is the same as Ask::tag, but it is a const fn, so a constant can hold a tagged question.

Source

pub fn answer( self, most_likely: &O, confidence: f64, probabilities: impl IntoIterator<Item = f64>, ) -> Result<ChoiceAnswer<O>, InvalidAnswer>
where O: PartialEq,

Builds the answer that a response with these values would give.

most_likely is the option that the API chose, confidence is its confidence, and probabilities has one probability for each option, in the order of the question. It’s for tests of your own decision code, and it goes through the same checks as a response from the API.

§Errors

Returns InvalidAnswer if most_likely is not an option of the question, if there is not one probability for each option, or if a value is not from 0 to 1.

§Examples
use system2::prelude::*;

let team = choice!("Which team should handle this ticket?", ["billing", "support"])
    .answer(&"billing", 0.8, [0.9, 0.1])?;
assert_eq!(*team.most_likely(), "billing");

Trait Implementations§

Source§

impl<O: Clone> Clone for Choice<O>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<O: Debug> Debug for Choice<O>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<O> QuestionSet for Choice<O>

Source§

type AnswerSet = ChoiceAnswer<O>

The answers of the set, with the shape of the set.

Auto Trait Implementations§

§

impl<O> Forget for Choice<O>

§

impl<O> Freeze for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: Freeze,

§

impl<O> Move for Choice<O>

§

impl<O> RefUnwindSafe for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: RefUnwindSafe,

§

impl<O> Send for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: Send,

§

impl<O> Sync for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: Sync,

§

impl<O> Unpin for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: Unpin,

§

impl<O> UnsafeUnpin for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: UnsafeUnpin,

§

impl<O> UnwindSafe for Choice<O>
where Table<(&'static str, Option<Json>, O), Entry<O>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<Q> Ask for Q
where Q: QuestionSet,

Source§

fn ask<S: Serialize + ?Sized>(self, state: &S) -> AskFuture<Self> ⓘ

Asks the set about a state, with the global client. Read more
Source§

fn ask_with_receipt<S: Serialize + ?Sized>( self, state: &S, ) -> AskWithReceiptFuture<Self> ⓘ

Asks the set about a state, and returns a Receipt next to the answers. Read more
Source§

fn tag<T>(self, tag: T) -> Tagged<Self, T>

Puts a tag next to the set, so that the answers come back next to it. Read more
Source§

impl<Q> Ask for Q
where Q: QuestionSet,

Source§

fn ask<S: Serialize + ?Sized>( self, state: &S, ) -> Result<Self::AnswerSet, AskError>

Asks the set about a state, with the global client, and waits for the answers. Read more
Source§

fn ask_with_receipt<S: Serialize + ?Sized>( self, state: &S, ) -> Result<(Self::AnswerSet, Receipt), AskError>

Asks the set about a state, and returns a Receipt next to the answers. Read more
Source§

fn tag<T>(self, tag: T) -> Tagged<Self, T>

Puts a tag next to the set, so that the answers come back next to it. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more