mirror of
https://github.com/roc-lang/roc.git
synced 2025-09-29 14:54:47 +00:00
Implement List.find
`List.find : List elem, (elem -> Bool) -> Result elem [ NotFound ]*` behaves as follows: ``` >>> List.find [1, 2, 3] (\n -> n > 2) Ok 2 >>> List.find [1, 2, 3] (\n -> n > 4) Err NotFound ``` We implement this as builtin in two phases. First, we call out to a pure-llvm-lowlevel `ListFindUnsafe` that returns a record indicating whether a satisfying element was found, and the value of that element (the value is all null bytes if the element wasn't found). Then, we lift that record to a `Result` via a standard construction of the can AST. Closes #1909
This commit is contained in:
parent
35df58c18f
commit
f65b174ab5
16 changed files with 417 additions and 8 deletions
|
@ -1093,6 +1093,42 @@ fn call_spec(
|
|||
|
||||
add_loop(builder, block, state_type, init_state, loop_body)
|
||||
}
|
||||
ListFindUnsafe { xs } => {
|
||||
let list = env.symbols[xs];
|
||||
|
||||
// Mark the list as being used by the "find" predicate function.
|
||||
// It may be the case that all elements in the list are used by the predicate.
|
||||
// Since `bag_get` assumes items are picked non-deterministically, this is
|
||||
// (probably?) enough to express that usage.
|
||||
let bag = builder.add_get_tuple_field(block, list, LIST_BAG_INDEX)?;
|
||||
let cell = builder.add_get_tuple_field(block, list, LIST_CELL_INDEX)?;
|
||||
let element = builder.add_bag_get(block, bag)?;
|
||||
let _bool = call_function!(builder, block, [element]);
|
||||
|
||||
// ListFindUnsafe returns { value: v, found: Bool=Int1 }
|
||||
let output_layouts =
|
||||
vec![arg_layouts[0].clone(), Layout::Builtin(Builtin::Int1)];
|
||||
let output_layout = Layout::Struct(&output_layouts);
|
||||
let output_type = layout_spec(builder, &output_layout)?;
|
||||
|
||||
// We may or may not use the element we got from the list in the output struct,
|
||||
// depending on whether we found the element to satisfy the "find" predicate.
|
||||
let found_branch = builder.add_block();
|
||||
let output_with_element =
|
||||
builder.add_unknown_with(found_branch, &[element], output_type)?;
|
||||
|
||||
let not_found_branch = builder.add_block();
|
||||
let output_without_element =
|
||||
builder.add_unknown_with(not_found_branch, &[], output_type)?;
|
||||
|
||||
builder.add_choice(
|
||||
block,
|
||||
&[
|
||||
BlockExpr(found_branch, output_with_element),
|
||||
BlockExpr(not_found_branch, output_without_element),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue