Closed
Description
Certain Ramda functions are unsafe. Take this quartet, for example:
R.head :: [a] -> a | Undefined -- unsafe
R.last :: [a] -> a | Undefined -- unsafe
R.tail :: [a] -> [a] -- safe, but misleading
R.init :: [a] -> [a] -- safe, but misleading
I suggest the following types:
R.head :: [a] -> Maybe a
R.last :: [a] -> Maybe a
R.tail :: [a] -> Maybe [a]
R.init :: [a] -> Maybe [a]
We could also provide the unsafe versions:
R.unsafeHead :: [a] -> a | Undefined
R.unsafeLast :: [a] -> a | Undefined
R.unsafeTail :: [a] -> [a]
R.unsafeInit :: [a] -> [a]
We'd also provide the following function which takes a default value as its first argument:
R.fromMaybe :: a -> Maybe a -> a
Let's consider a simple example: taking the first element of a [String]
of unknown length and converting it to upper-case.
// Naive solution (will throw if list is empty)
R.toUpper(R.head(list))
// Pre-emptive check
R.ifElse(R.isEmpty, R.always('<default>'), R.pipe(R.head, R.toUpperCase))(list)
// Maybe
R.fromMaybe('<default>', R.map(R.toUpperCase, R.head(list)))
It's cleaner and less error-prone to map over a maybe than to rely on checking for the empty list whenever one uses a member of this quartet.
These types are used by purescript-arrays. I'd like to Ramda do the same.
Metadata
Metadata
Assignees
Labels
No labels