Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Turn a list of coordinates into an ASCII graph?

Tags:

haskell

I'm stuck attempting to complete an assignment. It's the last question of the assignment, and I've been going at it for a while now with little progress. I need to turn an Image into an ASCII graph, where

type Point = (Int, Int)
type Image = [Point]

I have to write a function which takes an Image and returns a String. The output should be something like ".|...\n.xxx.\n-+x--\n.|...\n", which when outputted using putStr looks like

.|...
.xxx.
-+x--
.|...

With the origin denoted by +, the axes | and --, and the points 'x'.

The graph should always have a 1 point border around the coordinates, so when I'm printing the graph I need to be aware of the bounds of the coordinates. I have a function to get these.

I've also written a function, split, which takes a String and an integer, and inserts \n at every nth interval. The way I was thinking of solving the question was creating a blank graph with the correct positions for the axes, and then passing the blank graph to a new function to insert the points.

Can anyone assist me with this? Apologies if it's vague, I can provide any more details you may require.


1 Answers

Here are some things to think about:

  • What is an image, functionally speaking? Ignoring bounds for now, an image is a function from coordinates to whatever is shown on this coordinate. Try to come up with a type signature for images. Bonus points if you use type to call this an FImage. Think of such functions as your primary objects (remember, functions are first class citizens).
  • Implement the axes, as FImage. Note that you do not need any bounds for that. Isn’t that great?
  • Implement a function that takes an FImage and a Point, and produces an FImage that has the x in the right position.
  • Find out the bounds from a list of points. As always, always think first: What is the type signature of this?
  • Given an FImage and bounds, produce the final String. You may want to use List comprehensions here.
  • Put it all together. There is a fold hidden here! One of its arguments is going to be the list of points. What are the other arguments (the base case, and the combinating function). At this level of Haskell expertise, don’t worry too much whether it is a foldl or a foldr, both will work (if the types match).
  • Done :-)

Happy learning!

like image 53
Joachim Breitner Avatar answered Jan 29 '26 10:01

Joachim Breitner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!