Skip to content

Commit

Permalink
Running quicksort example
Browse files Browse the repository at this point in the history
  • Loading branch information
vkobinski committed Jun 21, 2024
1 parent 1405203 commit 65acef4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 33 deletions.
26 changes: 13 additions & 13 deletions crates/benda/src/types/book.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use std::cell::RefCell;
use std::ffi::CString;
use std::vec;

use bend::fun::{self, Book as BendBook, Name, Rule};
use bend::imp::{self, Expr, Stmt};
use indexmap::IndexMap;
use num_traits::ToPrimitive;
use pyo3::exceptions::PyException;
use pyo3::ffi::PyType_FromSpec;
use pyo3::ffi::{PyMethodDef, PyType_FromSpec};
use pyo3::inspect::types::{ModuleName, TypeInfo};
use pyo3::prelude::*;
use pyo3::types::{PyString, PyTuple, PyType};
use pyo3::types::{PyList, PyMapping, PyString, PyTuple, PyType};
use pyo3::PyTypeInfo;

use super::user_adt::UserAdt;
Expand All @@ -29,7 +28,7 @@ pub struct Term {
term: fun::Term,
}

fn get_list(lam: &fun::Term, vals: &mut Vec<String>) {
fn get_list(lam: &fun::Term, vals: &mut Vec<i32>) {
match lam {
fun::Term::Lam { tag, pat, bod } => {
get_list(bod, vals);
Expand All @@ -41,15 +40,15 @@ fn get_list(lam: &fun::Term, vals: &mut Vec<String>) {
fun::Term::Num { val } => match val {
fun::Num::U24(v) => {
if v.to_u32().unwrap() != 1 && v.to_u32().unwrap() != 0 {
vals.push(v.to_string())
vals.push(v.to_i32().unwrap())
}
}
fun::Num::I24(v) => {
if v.to_u32().unwrap() != 1 && v.to_u32().unwrap() != 0 {
vals.push(v.to_string())
vals.push(v.to_i32().unwrap())
}
}
fun::Num::F24(v) => vals.push(v.to_string()),
fun::Num::F24(v) => vals.push(v.to_i32().unwrap()),
},
_ => {}
}
Expand All @@ -64,7 +63,7 @@ impl Term {
fn __getattr__(&self, object: Bound<PyAny>) -> PyResult<PyObject> {
let py = object.py();

let mut vals: Vec<String> = vec![];
let mut vals: Vec<i32> = vec![];
get_list(&self.term, &mut vals);

Ok(vals.into_py(py))
Expand All @@ -75,6 +74,7 @@ impl Term {
#[derive(Clone, Debug)]
pub struct Ctr {
entire_name: String,
name: String,
fields: IndexMap<String, Option<Py<PyAny>>>,
}

Expand All @@ -94,11 +94,6 @@ impl Ctr {
})
}

fn __instancecheck__(&self, instance: Bound<PyAny>) -> bool {
dbg!("si");
todo!()
}

fn __str__(&self) -> String {
format!("Bend ADT: {}", self.entire_name)
}
Expand Down Expand Up @@ -129,6 +124,10 @@ impl Ctr {
return Ok(PyString::new_bound(py, &self.entire_name).into_py(py));
}

if &object.to_string() == "name" {
return Ok(PyString::new_bound(py, &self.name).into());
}

if let Ok(val) = object.to_string().parse::<usize>() {
let return_val = self.fields.get_index(val - 1);
if let Some(return_val) = return_val {
Expand Down Expand Up @@ -348,6 +347,7 @@ impl Book {
for (ctr_name, ctr_fields) in bend_adt.ctrs.iter() {
let new_name = ctr_name.split('/').last().unwrap().to_string();
let mut new_ctr = Ctr {
name: new_name.clone(),
entire_name: ctr_name.to_string(),
fields: IndexMap::new(),
};
Expand Down
53 changes: 33 additions & 20 deletions examples/quicksort.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from typing import TypeVar
import random

from .quicksort_mock import u24, List, List_Cons, List_Nil, mock_sort
from .quicksort_mock import u24, List_Cons, List_Nil, mock_sort
from .quicksort_mock import List as ListMock

T = TypeVar("T")


# import benda
# from benda import u24
# book = benda.load_book_from_file("./quicksort.bend")
import benda
from benda import U24
book = benda.load_book_from_file("./examples/quicksort.bend")
List = book.adts.List
# List_Nil = book.adts.List.Nil
# List_Cons = book.adts.List.Cons

Expand All @@ -21,32 +23,43 @@ def gen_list(n: int, max_value: int = 0xffffff) -> list[u24]:
return result


def to_cons_list(xs: list[int]) -> List[u24]:
def to_cons_list(xs: list[int]):
"""Converts a Python list to a Bend cons-list"""
result = List_Nil()
result = List.Nil()

hi = len(xs)
if hi == 0:
return result

while hi > 0:
hi -= 1
result = List_Cons(u24(xs[hi]), result)
result = List.Cons(u24(xs[hi]), result)

return result


def from_cons_list(xs: List[u24]) -> list[u24]:
# Ideal Syntax:
#def from_cons_list(xs: List[u24]) -> list[u24]:
# """Converts a Bend cons-list to a Python list"""
# result: list[u24] = []
# while True:
# match xs:
# case List_Nil():
# return result
# case List_Cons(value, tail):
# result.append(value)
# xs = tail

def from_cons_list(xs) -> list[u24]:
"""Converts a Bend cons-list to a Python list"""
result: list[u24] = []
while True:
match xs:
case List_Nil():
match xs.name:
case List.Nil.name:
return result
case List_Cons(value, tail):
case List.Cons.name:
value = xs.head
result.append(value)
xs = tail

xs = xs.tail

def main():
data = gen_list(10, 1000)
Expand All @@ -57,13 +70,13 @@ def main():

cons_list = to_cons_list(data)

# sorted_res = book.defs.Sort(cons_list)
# sorted_arr = from_cons_list(sorted_res)
# print("Result: ", sorted_arr)
sorted_res = book.defs.Sort(cons_list)
sorted_arr = sorted_res.list
print("Result: ", sorted_arr)

mocked_sorted = mock_sort(cons_list)
mocked_sorted_arr = from_cons_list(mocked_sorted)
print("Mocked: ", mocked_sorted_arr)
#mocked_sorted = mock_sort(cons_list)
#mocked_sorted_arr = mocked_from_cons_list(mocked_sorted)
#print("Mocked: ", mocked_sorted_arr)


if __name__ == "__main__":
Expand Down

0 comments on commit 65acef4

Please sign in to comment.