Hey everyone! I'm nearing the end of my second year at university, and I'm really struggling with my computer mathematics and declarative programming course. For one of my assignments, I have to create a coding project in a functional declarative style. The problem is, throughout the semester, we've focused mostly on the mathematical theory behind functional declarative programming but haven't had much practice with actual coding. I'm used to imperative programming, and the syntax of declarative programming is throwing me off completely.
I've seen examples online like "lst = [x*2 for x in lst]", but they don't cover more complex scenarios such as nested loops or branching. Plus, there's this confusing advice everywhere about not updating values throughout the program, which seems impossible to me. I've talked to my teacher and attended multiple support sessions, but I'm still baffled about how to implement declarative programming in practice. I get that I need to focus on the desired outcome rather than how to achieve it, but without a solid grasp of the syntax, I feel stuck. Any insights or guidance would be really appreciated! Thanks!
3 Answers
If you pick a functional programming language like Haskell or Clojure, you'll find tons of detailed examples that can help you understand better. Those languages make it easier to grasp functional concepts with full examples!
In functional programming, you don't update values directly; instead, you replace them. For example, if you have a user object and you want to change something, you create a whole new user object rather than just modifying fields. This is because objects in functional programming are often treated as immutable, meaning they can't change once created. So, instead of updating an existing 3x3 matrix, you'd create a new one every time a value changes. It might seem inefficient at first, but it helps avoid bugs and makes your code more predictable!
Have you thought about what problem you'd like to tackle with declarative programming? It helps to visualize a non-trivial scenario you're interested in.
For my assignment, I picked Gomoku, which is a board game where players place stones on a 15x15 board. The goal is to get five in a row. I'm struggling with how to handle board changes in a declarative way.
But isn’t replacing the same as updating? If I want to change a single cell in a matrix, creating a new one every time feels unnecessary. Why not just update the value directly? It seems like a lot of work for something simple.