#🔒 Translating some java into python

171 messages · Page 1 of 1 (latest)

torpid haven
#

I know pretty much nothing about java and im struggling to translate it into python, some help would be appreciated so i can get going with this interpreter.

grim forgeBOT
#

@torpid haven

Python help channel opened

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.

torpid haven
#

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

gleaming kiln
#

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

torpid haven
#

the tutorial is in java, i want to write it in python instead?

gleaming kiln
#

if you want to write in Python, why are you following a Java tutorial?

torpid haven
#

because it was suggested by nedbat and its a good tutorial

gleaming kiln
#

are you a Python beginner?

torpid haven
#

not really but sort of

#

im trying to learn more about how programming languages work by building an interpreter

gleaming kiln
#

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

torpid haven
#

are there any extremely good and informational ones? since the crafting interpreters one is pulling the topic apart very well

gleaming kiln
#

I'm afraid I haven't really looked

torpid haven
#

ah okay ill try asking in py discussion

left patio
#

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

shrewd haven
shrewd haven
# torpid haven my code so far: ```py class Lox: @staticmethod def main() ```

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.

torpid haven
shrewd haven
#
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.

torpid haven
shrewd haven
#

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

torpid haven
torpid haven
torpid haven
shrewd haven
#

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).

torpid haven
#

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

shrewd haven
#

start with something smaller?

torpid haven
#

like what?

shrewd haven
#

anything you find interesting

torpid haven
#

this is what i find interesting

shrewd haven
#

write a simple parser then?

#

you're going from 0 to 100 real quick by attempting to write your own interpreter

torpid haven
#

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

shrewd haven
torpid haven
#

thank you

torpid haven
shrewd haven
#

yes, that resource goes through how

#

with a bunch of tools/libraries you could benefit from if you want

torpid haven
#

where is the actual tutorial? this just seems like its listing libraries that you can use

shrewd haven
#

scroll down to

Useful Things To Know About Parsers

#

there are plenty of other resources, you could try googling till you find something better

tender tree
#

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

shrewd haven
#

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

crude dock
#

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.

torpid haven
#

might just make a calculator at this point 😭

tender tree
shrewd haven
torpid haven
#

ive made like 3 calculators before

#

1 terminal and 2 gui

crude dock
#

!projects has a lot of things you can check out as well if you need some ideas

grim forgeBOT
#
Kindling Projects

The Kindling projects page contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

grizzled stratus
crude dock
torpid haven
#

but lowkey might just give up on that too

grizzled stratus
#

okay, so your thread is about actually doing a proper calculator?

tender tree
#

Don't be afraid to learn something new

torpid haven
#
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

grizzled stratus
#

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.

torpid haven
#

just wanna learn parsing

#

cant find anything helpful

grizzled stratus
#

I'll see what I can find.

shrewd haven
#

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...

â–¶ Play video
#

seems to be a series of 4 videos in total though

torpid haven
#

thanks ill have a look

grizzled stratus
#

it looks decent, though it's very dense.

torpid haven
#

i think this is a great start though

grizzled stratus
#

very densely packed.

torpid haven
#

definitely can use this and then take it and modify it

grizzled stratus
#

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.

torpid haven
#

i mean i've been doing some research myself

#

i had a look at iter()

#

since i wasnt familiar with it

slender ibex
steel hazel
#

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.

torpid haven
#

your calculator is a billion times harder than mine

#

i just wanna add single digit numbers

steel hazel
#

Then you don't need a parser!

#

I thought you want to learn to write a parser.

torpid haven
#

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

torpid haven
#

ive literally just sat around everyday looking for something to do

steel hazel
#

Maybe instead of wanting something to do, you should be wanting to do something.

torpid haven
#

thats what im trying thats why im here

#

but everythings just too difficult

#

and the basic stuff isnt gonna help me

steel hazel
#

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.

torpid haven
#

how

#

this is my problem

steel hazel
#

What is the difficulty for you in this task?

torpid haven
#

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

steel hazel
#

How much Python do you know? Are you able to do string manipulation? Do you know how to get a number from a string?

torpid haven
#

could you iter() through it and then use the types of each character

gleaming bolt
#

@torpid haven there are a lot of implementations of lox in python you can take a look at them

torpid haven
#

im not fussed about lox right now really

#

i just wanna know the basic stuff

lavish valley
torpid haven
#

does iter() not loop over the characters?

lavish valley
#

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

torpid haven
#

with next()

lavish valley
torpid haven
#

idk

lavish valley
torpid haven
#

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

lavish valley
#

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

torpid haven
#

oh is it

#
for character in equation:
    if character in DIGITS:
steel hazel
torpid haven
#
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

lavish valley
torpid haven
#

but thats what i have right now

lavish valley
lavish valley
torpid haven
#

oh so i’ll define it outside

#

i need to get better at scopes i think

steel hazel
#

But let's focus on helping OP

steel hazel
torpid haven
torpid haven
#

@lavish valley i managed to get this!

Equation > 2 + 3 - 6 * 12 / 9
['2', '+', '3', '-', '6', '*', '12', '/', '9']
#

thats my tokens list

grim forgeBOT
#
Python help channel closed for inactivity

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.