11 Point-free style
Lesson goal Learn to write functions in point-free style with pipe, compose and curried functions, understand why ['1', '2', '3'].map(parseInt) gives [1, NaN, NaN], debug such pipelines with tap, and see when a named argument reads better.
Point-free style (also called tacit programming) is a way to define a function without mentioning its arguments. The new function is assembled from other functions through composition, currying and partial application. Instead of "take a user and return their name" we write "this is R.prop('name')".
A "point" here is not the dot in user.name but a function argument. The term comes from mathematics: in topology, functions act on spaces made of points, and a point-free definition of a function does not name the points, that is, the values it is applied to. So R.prop('name') is point-free even though it contains a dot.
The style relies on what we already know: a curried function returns a new function until it has all of its arguments, and pipe and compose chain functions into a pipeline. In Ramda functions are curried and, as a rule, take the data as their last argument, so R.filter(isOnline) is already a ready-made function waiting for a list.
// the course playground exposes Ramda as R
const users = [
{ name: 'John', status: 'online', age: 25 },
{ name: 'Alex', status: 'offline', age: 30 },
{ name: 'Angel', status: 'online', age: 16 },
]
// === with "points": the arguments are named explicitly ===
// getNameP :: Object -> String
const getNameP = (user) => user.name
// isOnlineP :: Object -> Boolean
const isOnlineP = (user) => user.status === 'online'
// onlineNamesP :: [Object] -> [String]
const onlineNamesP = (list) => list.filter((user) => isOnlineP(user)).map((user) => getNameP(user))
// === without "points": functions assembled from other functions ===
// getName :: Object -> String
const getName = R.prop('name')
// isOnline :: Object -> Boolean
// in current versions of Ramda propEq takes the value first and then the key,
// older versions had the opposite order
const isOnline = R.propEq('online', 'status')
// onlineNames :: [Object] -> [String]
const onlineNames = R.pipe(R.filter(isOnline), R.map(getName))
// the same with compose: the steps are written right to left
const onlineNamesC = R.compose(R.map(getName), R.filter(isOnline))
console.log(onlineNamesP(users).join(', ')) // John, Angel
console.log(onlineNames(users).join(', ')) // John, Angel
console.log(onlineNamesC(users).join(', ')) // John, Angel
// === your own curried functions work the same way ===
// add :: Number -> Number -> Number
const add = (a) => (b) => a + b
// with a point: the wrapper only passes n along
// incP :: Number -> Number
const incP = (n) => add(1)(n)
// without a point: add(1) is already a function waiting for the second number
// inc :: Number -> Number
const inc = add(1)
console.log(incP(41)) // 42
console.log(inc(41)) // 42The simplest step towards point-free code is dropping a wrapper: (x) => f(x) does the same as f itself. That is also the main trap of the style. The wrapper passes exactly one argument to f, while f without the wrapper receives everything the calling code passes.
The trap: extra arguments
Array.prototype.map calls its callback with three arguments: the element, its index and the whole array. parseInt takes two: a string and a radix. So ['1', '2', '3'].map(parseInt) actually calls parseInt('1', 0), parseInt('2', 1) and parseInt('3', 2), and returns [1, NaN, NaN].
// map passes the element, the index and the array to its callback,
// and the second parameter of parseInt is the radix
console.log(['1', '2', '3'].map(parseInt)) // [1, NaN, NaN]
// what is actually called
// radix 0 means "not set": a string without the 0x prefix is read as a decimal number
console.log(parseInt('1', 0)) // 1
// radix 1 is invalid: parseInt accepts radixes from 2 to 36
console.log(parseInt('2', 1)) // NaN
// there is no digit 3 in binary
console.log(parseInt('3', 2)) // NaN
// === how to fix it ===
// Number uses only its first argument
// it is stricter than parseInt: Number('12px') is NaN, while parseInt('12px', 10) is 12
console.log(['1', '2', '3'].map(Number)) // [1, 2, 3]
// bring the "point" back and pass the radix explicitly
console.log(['1', '2', '3'].map((str) => parseInt(str, 10))) // [1, 2, 3]
// R.map passes only the element to its callback
console.log(R.map(parseInt, ['1', '2', '3'])) // [1, 2, 3]
// R.unary keeps one argument of a function and drops the rest
console.log(['1', '2', '3'].map(R.unary(parseInt))) // [1, 2, 3]forEach, filter and other array methods behave the same way. With object methods the trap is different: arr.map(obj.method) calls the method without its object, and this inside it will be wrong. There is also a delayed version: if a function passed to map without a wrapper later gains an optional second parameter, the index will silently start arriving in it.
Readability and debugging
Point-free code is shorter but not always clearer: to read it you have to remember the signature of every function. R.lte(18) is the function age => 18 <= age, and R.gt(18) is age => 18 > age. So R.filter(R.gt(18)) keeps those younger than 18, even though it reads as "greater than 18".
const users = [
{ name: 'John', status: 'online', age: 25 },
{ name: 'Alex', status: 'offline', age: 30 },
{ name: 'Angel', status: 'online', age: 16 },
]
// point-free: you need to know that R.lte(18) is age => 18 <= age
// isAdultOnline :: Object -> Boolean
const isAdultOnline = R.both(R.propSatisfies(R.lte(18), 'age'), R.propEq('online', 'status'))
// with a point: the condition is visible at once
// isAdultOnlineP :: Object -> Boolean
const isAdultOnlineP = (user) => user.age >= 18 && user.status === 'online'
console.log(users.filter(isAdultOnline).length) // 1
console.log(users.filter(isAdultOnlineP).length) // 1
// R.gt(18) reads as "greater than 18", but it means age => 18 > age
// ages :: [Number]
const ages = [10, 18, 20, 30]
console.log(R.filter(R.gt(18), ages).join(', ')) // 10
// with a named argument you can't get it wrong
console.log(ages.filter((age) => age > 18).join(', ')) // 20, 30The second cost is debugging. A point-free function has no body to put a breakpoint or a console.log in. You can't put console.log itself into the pipeline either: it returns undefined, and the next step receives that instead of the data. tap helps here: it calls the given function for its side effect and returns the argument unchanged. There is more about it in the "Side effects in function composition" lesson, and Ramda has a ready-made R.tap.
const users = [
{ name: 'John', status: 'online', age: 25 },
{ name: 'Alex', status: 'offline', age: 30 },
{ name: 'Angel', status: 'online', age: 16 },
]
// tap :: (a -> *) -> a -> a
// calls fn for its side effect and returns x unchanged
const tap = (fn) => (x) => {
fn(x)
return x
}
// log :: String -> a -> a
const log = (label) => tap((value) => console.log(label + ': ' + JSON.stringify(value)))
// onlineNames :: [Object] -> String
const onlineNames = R.pipe(
R.filter(R.propEq('online', 'status')),
log('after filter'), // prints the intermediate result
R.map(R.prop('name')),
log('after map'),
R.join(', '),
)
console.log(onlineNames(users))
// after filter: [{"name":"John","status":"online","age":25},{"name":"Angel","status":"online","age":16}]
// after map: ["John","Angel"]
// John, AngelWhen not to use it
Point-free style is a tool, not a goal. It works well where a pipeline reads as a list of steps: "keep those who are online, take their names". A named argument is better in these cases:
- the argument is needed in several places: (user) => user.firstName + ' ' + user.lastName is simpler than the same function built with R.converge;
- a point-free version requires reordering arguments with R.flip or the R.__ placeholder;
- the function you pass without a wrapper takes optional parameters or depends on this, like parseInt and object methods;
- the argument's name tells the reader what data the function works with.
A practical rule: build a pipeline out of ready-made functions without "points", and if that takes flip, converge or placeholders, name the argument.
Key points
- Point-free style defines a function without mentioning its arguments: it is assembled from other functions through composition and currying, for example R.pipe(R.filter(isOnline), R.map(R.prop('name'))).
- The wrapper (x) => f(x) can be replaced with f only if f won't take extra arguments: ['1', '2', '3'].map(parseInt) gives [1, NaN, NaN] because map also passes the index and the array.
- The trap is avoided with Number, an explicit arrow function with a radix, R.map, which passes only the element, or R.unary.
- A point-free pipeline is debugged with tap: it performs a side effect and returns the argument unchanged.
- If a point-free version needs flip, converge or placeholders, or the argument's name explains something, a named argument reads better.
Exercises
Exercise 1
Rewrite getTitleP, isInStockP, toUpperP and availableTitlesP in point-free style: getTitle, isInStock, toUpper and availableTitles must not mention their arguments. R.prop, R.propEq (value first, then key), R.toUpper, R.filter, R.map and R.pipe will come in handy. Print the result of both versions and make sure it is the same.
Starter code
const products = [
{ title: 'Book', price: 400, inStock: true },
{ title: 'Pen', price: 50, inStock: false },
{ title: 'Lamp', price: 1200, inStock: true },
{ title: 'Mug', price: 300, inStock: true },
]
// versions with "points"
// getTitleP :: Object -> String
const getTitleP = (product) => product.title
// isInStockP :: Object -> Boolean
const isInStockP = (product) => product.inStock === true
// toUpperP :: String -> String
const toUpperP = (str) => str.toUpperCase()
// availableTitlesP :: [Object] -> [String]
const availableTitlesP = (list) => list.filter((product) => isInStockP(product)).map((product) => toUpperP(getTitleP(product)))
// your code: getTitle, isInStock, toUpper, availableTitles
console.log(availableTitlesP(products).join(', '))
console.log(availableTitles(products).join(', '))Expected output
BOOK, LAMP, MUG BOOK, LAMP, MUG
Show solution
const products = [
{ title: 'Book', price: 400, inStock: true },
{ title: 'Pen', price: 50, inStock: false },
{ title: 'Lamp', price: 1200, inStock: true },
{ title: 'Mug', price: 300, inStock: true },
]
// versions with "points"
// getTitleP :: Object -> String
const getTitleP = (product) => product.title
// isInStockP :: Object -> Boolean
const isInStockP = (product) => product.inStock === true
// toUpperP :: String -> String
const toUpperP = (str) => str.toUpperCase()
// availableTitlesP :: [Object] -> [String]
const availableTitlesP = (list) => list.filter((product) => isInStockP(product)).map((product) => toUpperP(getTitleP(product)))
// getTitle :: Object -> String
const getTitle = R.prop('title')
// isInStock :: Object -> Boolean
const isInStock = R.propEq(true, 'inStock')
// a string method can't be passed without a wrapper: Ramda has a matching function
// toUpper :: String -> String
const toUpper = R.toUpper
// availableTitles :: [Object] -> [String]
// two steps in a row for each product are a pipeline too
const availableTitles = R.pipe(R.filter(isInStock), R.map(R.pipe(getTitle, toUpper)))
console.log(availableTitlesP(products).join(', '))
console.log(availableTitles(products).join(', '))Exercise 2
sumCsv should add up the numbers in the string '10,20,30' and print 60, but it prints NaN. The starter has tap and a log helper. Build a debug version sumCsvDebug: the same pipeline with log after each step. Find the step where the data goes wrong, explain why, and fix sumCsv so that it stays point-free. Print the result of sumCsvDebug('10,20,30'), then that of the fixed sumCsv.
Starter code
// tap :: (a -> *) -> a -> a
const tap = (fn) => (x) => {
fn(x)
return x
}
// log :: String -> a -> a
// R.toString shows NaN, while JSON.stringify would turn it into null
const log = (label) => tap((value) => console.log(label + ': ' + R.toString(value)))
// map in the spirit of the "Currying" lesson: passes fn to the array method as is
// map :: (a -> b) -> [a] -> [b]
const map = (fn) => (arr) => arr.map(fn)
// split :: String -> String -> [String]
const split = (separator) => (str) => str.split(separator)
// sum :: [Number] -> Number
const sum = (arr) => arr.reduce((acc, n) => acc + n, 0)
// sumCsv :: String -> Number
const sumCsv = R.pipe(split(','), map(parseInt), sum)
// your code: sumCsvDebug and the fixed sumCsv
console.log(sumCsv('10,20,30'))Expected output
split: ["10", "20", "30"] map: [10, NaN, NaN] NaN 60
Show solution
// tap :: (a -> *) -> a -> a
const tap = (fn) => (x) => {
fn(x)
return x
}
// log :: String -> a -> a
// R.toString shows NaN, while JSON.stringify would turn it into null
const log = (label) => tap((value) => console.log(label + ': ' + R.toString(value)))
// map in the spirit of the "Currying" lesson: passes fn to the array method as is
// map :: (a -> b) -> [a] -> [b]
const map = (fn) => (arr) => arr.map(fn)
// split :: String -> String -> [String]
const split = (separator) => (str) => str.split(separator)
// sum :: [Number] -> Number
const sum = (arr) => arr.reduce((acc, n) => acc + n, 0)
// the debug version: the same pipeline with log after each step
const sumCsvDebug = R.pipe(split(','), log('split'), map(parseInt), log('map'), sum)
console.log(sumCsvDebug('10,20,30'))
// the data breaks after map: the array method also passes the index to parseInt,
// and it becomes the radix: parseInt('20', 1) and parseInt('30', 2) give NaN
// Number uses only its first argument, and the pipeline stays point-free
// sumCsv :: String -> Number
const sumCsv = R.pipe(split(','), map(Number), sum)
console.log(sumCsv('10,20,30'))Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.