How can you write a parameterless function in Ramda using a point-free style?

Take a look at this functioning code snippet:

var randNum = x => () => Math.floor(x*Math.random());
var random10 = randNum(10)
times(random10, 10) // => [6, 3, 7, 0, 9, 1, 7, 2, 6, 0]

The function randNum creates a random number generator that will output an integer between 0 and N-1 when invoked. It serves as a factory for specific RNGs.

While experimenting with ramda.js and delving into functional programming concepts, I wondered if it's possible to refactor randNum into a point-free style using ramda?

One approach could be:

var unsuccessfulTry = pipe(multiply(Math.random()), Math.floor)

This implementation meets the "point-free style" criteria, but it diverges from the behavior of randNum: executing unsuccessfulTry(10) only results in a single random number instead of generating random numbers within the specified range each time it's called.

Despite numerous attempts, I haven't found the right combination of ramda functions to achieve a point-free rewrite. I'm unsure if this is due to my limitations or perhaps some intricacy related to utilizing random, which compromises referential transparency and might conflict with a point-free approach.

Update

Following discussions with Denys, here's a slight modification to the solution I came up with:

randNum = pipe(always, of, append(Math.random), useWith(pipe(multiply, Math.floor)), partial(__,[1,1]))

Answer №1

This function provides a helpful way to abstract another function in order to re-evaluate its arguments every time it is called.

thunk = fn => R.curryN(fn.length, (...args) => () => fn(...args))

The primary purpose of this new function is to trigger a side effect within the specified fn function.

With the introduction of the thunk function, we can create a function like randN as follows:

randN = thunk(R.pipe(S.S(R.multiply, Math.random), Math.floor))

R.times(randN(10), 5) // for example: [1, 6, 9, 4, 5]

Please note that S.S refers to the S combinator from Sanctuary, which essentially performs the same functionality as

R.converge(multiply, [Math.random, identity])
.

It is worth mentioning that adopting a point-free solution should only be considered if it truly enhances the clarity and readability of a function.

Answer №2

Exploring functional programming with a specific library can sometimes blur the lines between the unique characteristics of the library and the fundamental principles of the functional paradigm. However, in practical application, Ramda proves to be an invaluable tool, acting as a bridge between imperative programming and the abstract world of Fantasy Land in the realm of Javascript :D

Here is a manual approach:

// several versatile, reusable functions:
const comp = f => g => x => f(g(x)); // combining mathematical functions
const comp2 = comp(comp)(comp); // composition for binary functions
const flip = f => x => y => f(y)(x); // reversing arguments
const mul = y => x => x * y; // operator function

// constructing a point-free function:
const randN = comp2(Math.floor)(flip(comp(mul)(Math.random)));

let rand10 = randN(10); // generating random numbers
for (let i = 0; i < 10; i++) console.log(rand10());

It is important to note that randN is inherently impure due to the nature of random number generation being considered impure.

Answer №3

Create a function that generates an array of random numbers between 0 and 10 using Ramda library in JavaScript. The code snippet is as follows:
var randN = R.converge(R.partial, [R.wrap(R.pipe(R.converge(R.multiply, [Math.random, R.identity]), Math.floor), R.identity), R.of])
var rand10 = randN(10)
alert(R.times(rand10, 10)) // => [3, 1, 7, 5, 7, 5, 8, 4, 7, 2]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.19.1/ramda.js"></script>

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

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Basic PHP code converted into a JavaScript function for an onSubmit event within an HTML form

I have been trying to figure this out for hours. The goal is to submit a form only if one of the inputs matches a PHP echo. To simplify the script, it looks something like this: <head> </head> <body> <?php $A = rand(0,10); $B = r ...

Send JSON data that has been refined utilizing jQuery

I am attempting to create a filtered JSON response using jQuery following a successful GET request of the original JSON response. The initial JSON response is an array of products from our Shopify store for the specific collection page the user is viewing. ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

Javascript downloadable content available for download

<div class="center"data-role="content" id="content" > <a href="#flappy" data-transition="slide" >Avoid Becoming a Terrorist</a> </div> <div id="flappy" > <center> <div id="page"> ...

Attempting to get a webGL game downloaded from Unity to automatically enter fullscreen mode

Can someone help me with my Unity webGL game issue? I downloaded it from the internet, but I'm not sure what version of Unity was used to create it. When the game starts playing, it displays in a small canvas along with other elements like the Unity ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

Sequelize - issue with foreign key in create include results in null value

When using the create include method, the foreign key is returning null, while the rest of the data is successfully saved from the passed object. This is my transaction model setup: module.exports = (sequelize, DataTypes) => { const Transaction = ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

What is the proper way to initialize a two-dimensional array in JavaScript?

I recently received a suggestion on this question to create a two-dimensional array in my jQuery quiz application. However, I seem to be encountering an error while running the code. I suspect the issue might be due to incorrect formatting or a lack of ini ...

Error code 12004 encountered during the execution of a service request

While working on a service call in my JavaScript code that retrieves XML data using XMLHttpRequest, everything runs smoothly in Chrome and Firefox, successfully fetching the data over HTTPS. However, when attempting to execute the same code in IE11, it ret ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

What is the best way to showcase the information from this API on an HTML page using Vanilla JavaScript?

I am currently working on implementing an AJAX call to fetch data from a movie API online. Below is the HTML code I have written for this: <html> <head> <meta charset=utf-8> <title>Movie Database</title> ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

What is the best way to display a SolidJS component on the screen?

I am currently working on a unique menu design for my application. The concept involves rendering a functional component within an element created in the body using createRoot and render methods. https://i.stack.imgur.com/g6Ofv.png export function create ...

Using a personalized function in JQuery

I need to execute a JavaScript function I created after a JQuery event has been triggered. The function in question is called scrambleDot, and I defined it previously like so:var scrambleDot = new function() { //my code }. Here's the attempted implem ...

How to include subdirectories in a TypeScript npm module

I am in the process of developing a package for npm and I would like it to be imported in the following manner: import myPackage from 'my-package'; import { subFunction1, subFunction2 } from 'my-package/subfunctions'; Upon trying to u ...