How about representing a two-dimensional array in a point-free manner?

Exploring functional/tacit style programming, specifically implementing the snake game (example: )

The main issue at hand involves processing an array of strings like:

[
 ['2 '],
 ['10']
]

and obtaining a list of coordinates in numerical order of the 'value'. In this context, 0 represents the head of the snake, 2 the tail, and the whole structure represents the board.

With this in mind, the following function was created:

var findSnake = function(rendered_board) {
  return r.map(function(x) {
    return r.map(function (y) {
      return {
        x: x,
        y: y,
        val: rendered_board[x][y]
      };
    })(r.keys(r.split('', rendered_board[x])));
  })(r.keys(rendered_board));
};

As a result, the following output is obtained:


[ [ { x: '0', y: '0', val: '2' }, { x: '0', y: '1', val: ' ' } ],
  [ { x: '1', y: '0', val: '1' }, { x: '1', y: '1', val: '0' } ] ]

After sorting, this provides the desired list of coordinates. Despite its functionality, there are concerns regarding coding style.

Is it possible to rewrite findSnake using a point-free style? Are there more idiomatic solutions to this problem?

Answer №1

It's no surprise that transforming this into a concise, point-free solution would be overly complex. I attempted a simplified version of the problem, but even that was messy and didn't seem worth pursuing.

If we take a look at this initial function:

var fn = function(list) {
    return R.map(function(y) {
        return {
            y: y
        };
    }, list);
}

...which is clearly a subproblem of the larger issue, we can attempt to rewrite it like so:

var fn = R.pipe(R.converge(
    R.zip, 
    R.pipe(R.length, R.repeat('y')), 
    R.identity
), R.map(R.apply(R.createMapEntry)));

(For intermediate steps, refer to the REPL)

However, when using ES6 syntax, the approach seems quite counterproductive:

var fn = R.map(y => ({y});

This is why I opt for a point-free style when appropriate, but I don't force it into every situation.


Update

With version 0.18, Ramda changed `createMapEntry` to `objOf` and converted `converge` into a binary function. As a result, the previous code snippet no longer functions. The REPL link has also been updated. You can view the revised code in the REPL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

Analyzing Strings: Identifying matching words between two arrays and eliminating duplicates

Seeking advice on how to modify my code to compare and remove common words from two arrays. The objective is to read an "input" file, copy its contents to create an "output1" file, then compare the "output1" array with a "stopword" array to eliminate match ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

Tips for updating information when a button is chosen

Hello everyone, I need some help with a form that has three select buttons. The button labeled "Distribute" is already selected when the page loads, and it contains information about full name, password, and location. How can I use JavaScript to create a c ...

Is there a way for me to manually initiate a digest cycle on the parent scope based on my instructions?

I am struggling with getting a directive to render automatically when a change is made to the underlying model programmatically. Using $scope.$apply seems like the right approach, but unfortunately it's not working as expected. The directive only rend ...

Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing betwe ...

What is the best method for importing several components from a directory in ReactJS?

I'm looking for a way to import multiple React components from a directory without having to export them separately in an index.js file. Here's the structure of my directory: src/ components/ comp1.js comp2.js comp3.js ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

I'm having some unexpected reflections with the threejs cube camera

I'm currently experimenting with creating an object that reflects on all sides. Although I've made progress, I seem to be encountering some issues. At certain angles, I can only see partial reflections and the scale of the reflection is much larg ...

Guide on storing a promise response in an external object in VUE

I am currently working on integrating the higchart network graph in vue. Everything seems to be functioning properly with static data. However, when I attempt to retrieve data using axios, it fails to work. export default { data() { return { ne ...

Using jQuery to dynamically populate select options based on JSON data

I have been testing and searching for a solution to my issue, but it still doesn't work. Any help would be greatly appreciated. I have three select options implemented in PHP like this: <div class="control-group" id="merkPrinter"> <label cl ...

Implement image uploading feature with Ant Design library in a React JS application

I need assistance with a basic application that allows users to upload images. Once the image is uploaded and the user clicks on the get data from upload button, the result should be displayed in the console as console.log("Received values of form: ", valu ...

Unable to retrieve elements from the eBay website using JavaScript within a Chrome extension

I recently developed a Chrome extension that scrapes all orders from an eBay orders page. It was working flawlessly last month, but suddenly I am facing issues accessing some elements. Here is the snippet of code causing trouble: let elGridComp = document ...

Cease the ongoing Ajax request and switch to a new Ajax call immediately

Within this code snippet, I am capturing user input for typing and then searching it in a database. However, with each character entered by the user, a new AJAX request is triggered without canceling the previous one. My objective is to have the search fu ...

"Redirecting to an HTML page from the POST method is not supported in the Flask backend and Vanilla JS frontend setup

Utilizing the selected dropdown value from the frontend to perform calculations on the backend, resulting in an HTML page being returned. It's worth noting that no response is needed from the POST method, such as using return jsonify. Currently, I am ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...