Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement list index #324

Merged
merged 1 commit into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions opshin/tests/test_stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,28 @@ def validator(x: Dict[int, bytes], y: int) -> bytes:
exp = None
self.assertEqual(ret, exp, "dict[] returned wrong value")

@given(st.data())
def test_list_index(self, data):
source_code = """
def validator(x: List[int], z: int) -> int:
return x.index(z)
"""
xs = data.draw(st.lists(st.integers()))
z = data.draw(
st.one_of(st.sampled_from(xs), st.integers())
if len(xs) > 0
else st.integers()
)
try:
ret = eval_uplc_value(source_code, xs, z)
except RuntimeError as e:
ret = None
try:
exp = xs.index(z)
except ValueError:
exp = None
self.assertEqual(ret, exp, "list.index returned wrong value")

@given(xs=st.dictionaries(st.integers(), st.binary()))
def test_dict_keys(self, xs):
source_code = """
Expand Down
42 changes: 42 additions & 0 deletions opshin/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,48 @@ class ListType(ClassType):
def __ge__(self, other):
return isinstance(other, ListType) and self.typ >= other.typ

def attribute_type(self, attr) -> "Type":
if attr == "index":
return InstanceType(
FunctionType(frozenlist([self.typ]), IntegerInstanceType)
)
super().attribute_type(attr)

def attribute(self, attr) -> plt.AST:
if attr == "index":
return OLambda(
["self", "x"],
OLet(
[("x", plt.Force(OVar("x")))],
plt.Apply(
plt.RecFun(
OLambda(
["index", "xs", "a"],
plt.IteNullList(
OVar("xs"),
plt.TraceError("Did not find element in list"),
plt.Ite(
plt.EqualsInteger(
OVar("x"), plt.HeadList(OVar("xs"))
),
OVar("a"),
plt.Apply(
OVar("index"),
OVar("index"),
plt.TailList(OVar("xs")),
plt.AddInteger(OVar("a"), plt.Integer(1)),
),
),
),
),
),
OVar("self"),
plt.Integer(0),
),
),
)
super().attribute(attr)

def stringify(self, recursive: bool = False) -> plt.AST:
return OLambda(
["self"],
Expand Down