#🔒 Translating some java into python
171 messages · Page 1 of 1 (latest)
@torpid haven
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
my code so far:
class Lox:
@staticmethod
def main()
thats the book i am following along with
public class Lox {
public static void main(String[] args) throws IOException {
if (args.length > 1) {
System.out.println("Usage: jlox [script]");
System.exit(64);
} else if (args.length == 1) {
runFile(args[0]);
} else {
runPrompt();
}
}
}
i need some help with the parameters of the main function
and the throw which i assume is error handling
why do you even have a class for that
that's not how you write Python code
just write that code directly in the script
the tutorial is in java, i want to write it in python instead?
if you want to write in Python, why are you following a Java tutorial?
because it was suggested by nedbat and its a good tutorial
are you a Python beginner?
not really but sort of
im trying to learn more about how programming languages work by building an interpreter
that's a pretty high level task for someone not yet comfortable with the language
and I believe there are tutorials for building interpreters in Python
are there any extremely good and informational ones? since the crafting interpreters one is pulling the topic apart very well
I'm afraid I haven't really looked
ah okay ill try asking in py discussion
Python does not oblige u to use class every where and u can start with a simple main function. Translating from one language to the other requires base knowledge for both languages and I think is not suitable for beginner
that's a book for creating interpeters/compilers in general, they're not for teaching a specific language, it just so happen they use c and java. i've used that book and followed it along in both rust and swift before.
you need to be aware that you shouldn't translate the code 1:1 because different languages work differently, it's not enough with just changing the syntax. python has no main entry point besides the file that's being run, that means whatever is in the main function of the java code can be in the top level of your main python file (main here indicating the python file you're invoking with the python interpreter)
i wouldn't really recommend this as a project for you to learn python, but rather for learning how to create an interpreter/compiler where you happen to already be familiar with python instead of c/java.
i am confident with python just not interpreters or java
you can't write python like java, you have to write python like python
class Lox:
@staticmethod
def main():
...
```what will call this main function?
in java, it's called automatically
in python it's not, so you'd have to call it yourself```py
class Lox:
@staticmethod
def main():
...
Lox.main()
at which point, the class is entirely redundant
you may be confident, and i don't intend to tear that confidence, but you do clearly lack some foundational experience that tutorial will require you to know given you're not actually following their implementation but rather trying to interpret and write your own.
well i’ll be honest idk how else to learn
if your goal is to learn how to create interpreters and/or compilers, why couldn't you just follow the tutorial in c or java?
if your goal is to learn python, then find a tutorial that teaches you python instead
if you intend to do both, start with the latter and work your way up to the former
i don’t want to learn java or c i want an interpreter built in python as that’s the language i wanna work in
yeah but what should i do to learn python more
i’m not new to python, i don’t know what to learn
how and where the main execution point of your program is, is a basic starting block you should know, in python that'd be any script you directly invoke or a __main__ file, as opposed to most AoT or JIT compiled languages that have a special main function that may or may not have to be a method on a class. if you truly do think you have the required experience in python, you should be able to write your implementations without having to translate the java/c code given the actual details are explained in text (the book is language agnostic, they only use java/c as examples). even so, if you did have the required python experience, that should be enough to cross over to java/c where you can at least be able to filter out the bits you know you'd need in python (which is the logic code) and the bits you'd know wont translate to python (java/c specific features).
i dont know what else to do then
this is the problem i have
what do i do if i dont have the experience to learn it
i cant program anything because i dont know it all
and to learn it i need to do it, but i cant
start with something smaller?
like what?
anything you find interesting
this is what i find interesting
write a simple parser then?
you're going from 0 to 100 real quick by attempting to write your own interpreter
well thats what this tutorial was supposed to be but its just the whole interpreter instead
i asked for help on where to find out how i can write a parser and this is what i got sent
this seems like a nice little getting started resource https://tomassetti.me/parsing-in-python/ then pick something simpler to parse, like math expressions, an ini file parser, csv parser, etc...
thank you
is there anyway to do it without a library
yes, that resource goes through how
with a bunch of tools/libraries you could benefit from if you want
where is the actual tutorial? this just seems like its listing libraries that you can use
idk how else to help you man it literally goes through the fundamental things you need to understand about parsers
scroll down to
Useful Things To Know About Parsers
there are plenty of other resources, you could try googling till you find something better
Crafting Interpreters is the best resource I'm aware of for learning how to make your own programming language. I'd suggest investing the effort to get good enough at Java to at least follow the code examples in the book
that's what i suggested in an essence but fallbacked to recommending something smaller like a csv parser - they don't seem to be interested in investing some time in java or c
you don't need to translate the code line by line, but it's important that you know how to write code equivalent to what they're showing.
there's a list of lox interpreters written in Python listed here: https://github.com/munificent/craftinginterpreters/wiki/Lox-implementations#python, if you're really stuck on something maybe referencing what one of these have done could help
might just make a calculator at this point ðŸ˜
The Python equivalent of this is: ```py
import sys
if len(sys.argv) > 2:
print("Usage: jlox [script]")
sys.exit(64)
elif len(sys.argv) == 2:
run_file(sys.argv[1])
else:
run_prompt()
actually that's a good start, you'll have to parse math expressions
!projects has a lot of things you can check out as well if you need some ideas
The Kindling projects page contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
with actual parsing logic? i.e. PEMDAS rules, etc?
do they handle precedence? (e.g will (5+2*3) give you the right answer)
no, im trying to make a maths expression parser that makes an AST now
but lowkey might just give up on that too
okay, so your thread is about actually doing a proper calculator?
Genuinely, you'll notice that the Python version and the Java version are extremely similar. Python and Java are very similar languages
Don't be afraid to learn something new
import sys
equation = sys.argv
if len(equation) > 1:
print("Usage: parser [equation]")
elif len(equation) == 1:
pass
else:
pass
tokens = equation.split(sep=None, maxsplit=-1)
thats what i did
i just want it to do like 8+2
but first i gotta make it an AST
lemme see if I can find something
I remember Guido himself wrote something about parsing with the new PEG parser and a special form of packratt parsing (memoization) that allows left-recursion ... but I think that one is too advanced.
I'll see what I can find.
i found this video if it'd be in interest https://www.youtube.com/watch?v=88lmIMHhYNs
In this short series, we are going to be writing a simple interpreter in Python that can understand and process basic math calculations.
This is useful to learn how to write a program that can understand a human-readable format, and this knowledge can be expanded to creating your own data language, programming language, etc.
You can obtain the...
seems to be a series of 4 videos in total though
thanks ill have a look
it looks decent, though it's very dense.
what do you mean by dense?
i think this is a great start though
very densely packed.
definitely can use this and then take it and modify it
the information doesn't go into much details or reasonings for specific things, as far as I can tell
but I suppose that can be fine.
i mean i've been doing some research myself
i had a look at iter()
since i wasnt familiar with it
For extended reading, search shunting yard algorithm
Don't look down on calculators. Take it far enough, that's a tiny language you have right there.
I recommend a recursive descent parser. It's efficient (O(n) on input size) and very flexible to work with. You can add operators, modify precedences and change associativity just by tweaking a few numbers.
Check my project (link in bio) if you want to see how it works.
your calculator is a billion times harder than mine
i just wanna add single digit numbers
i dont even know what i want to do anymore
im just bored
i've had 5 weeks off school and start a new one in 5 weeks
im so bored
that is what i wanted
ive literally just sat around everyday looking for something to do
Maybe instead of wanting something to do, you should be wanting to do something.
thats what im trying thats why im here
but everythings just too difficult
and the basic stuff isnt gonna help me
Ramp up slowly.
First, write something that does multiple digit integers, + and *
31 + 42 * 5 + 6
OK you have something to do, go do it.
What is the difficulty for you in this task?
well i dont know how to get my computer to understand what each number is and what to do with symbols
since it doesnt know ive got to tell it
How much Python do you know? Are you able to do string manipulation? Do you know how to get a number from a string?
could you iter() through it and then use the types of each character
@torpid haven there are a lot of implementations of lox in python you can take a look at them
im not sure why would you explicitly use iter, just loop over the characters in the string, keep a variable to add related characters into, "dump" it each time you meet something that logically "splits" tokens (an operator, or a parentheses), and skip whitespace
does iter() not loop over the characters?
for parsing expressions with operator precedence, you can use a recursive approach with the precedence of the previous operator as an argument, so in cases like 2+3*5+6, when you meet the *, the next parse would know that * (an operator with higher precedence) was before it, therefore it should return early instead of binding
with next()
why would you explicitly use the iterator interface instead of just a for loop?
for character in string:
idk
this problem is over-blown-up by academic people trying to write "the most efficient" parsers, and it doesnt need any fancy terminology or years of experience
parsing is the smallest problem of language development, yet resources spend a lot of time on it
literally a "loop and go-left sometimes parser" is enough
sounds like im gonna have great fun with language development 🥹
tokens = []
DIGITS = "0123456789"
equation = input("Equation > ")
for character in equation:
current_char = equation[character]
if current_char in DIGITS:
thats what ive got
am i on the right track or no
character is already the character, not an index, so you dont need the [character] part
but yes, you should check what kind of character you have, and either add it to some buffer or split based on that
Yes to this. With slight modifications to account for associativity.
tokens = []
DIGITS = "0123456789"
equation = input("Equation > ")
for character in equation:
store = None
decimal_count = 0
if character in DIGITS:
store += character
elif character == ".":
store += character
if decimal_count > 1:
raise TypeError(f"Illegal characters entered, a value contains 2 or more decimal points")
gonna go eat dinner
the slight modification is literally > vs >=, in this case
and a table for operator associativity when they have operators where that would matter (e.g. exponentiation)
but thats what i have right now
you're resetting store each character, so its never going to actually store anything
is it not adding it?
with +=
you have store = None at the start of each iteration
I have a different precedence level for entering a next call, vs while being in the call itself. Not quite as simple as < vs <=
But let's focus on helping OP
If I may suggest, you may want to ramp down a bit and work on basic Python exercises instead.
they’re boring and just me repeating myself
@lavish valley i managed to get this!
Equation > 2 + 3 - 6 * 12 / 9
['2', '+', '3', '-', '6', '*', '12', '/', '9']
thats my tokens list
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.