- allow_reverse: logical, whether to allow ranges like "10-7" and reverse them
if (is.na(input_string) || str_trim(input_string) == "") {
return(numeric())
}
parts <- str_split(input_string, ",")[[1]]
parts <- str_trim(parts)
result <- numeric()
for (part in parts) {
if (str_detect(part, "-")) {
range_parts <- str_split(part, "-")[[1]]
code
if (length(range_parts) != 2) {
if (warn) warning(paste("Invalid range format (too many hyphens):", part, ". Skipping."))
next
}
start <- as.integer(range_parts[1])
end <- as.integer(range_parts[2])
if (is.na(start) || is.na(end)) {
if (warn) warning(paste("Non-integer range values:", part, ". Skipping."))
next
}
if (start > end && allow_reverse) {
tmp <- start
start <- end
end <- tmp
}
if (start <= end) {
# Apply bounds
bounded_start <- max(start, min_val)
bounded_end <- min(end, max_val)
if (bounded_start <= bounded_end) {
result <- c(result, bounded_start:bounded_end)
} else {
if (warn) warning(paste("Range outside bounds after adjustment:", part, ". Skipping."))
}
} else {
if (warn) warning(paste("Invalid range (start > end):", part, ". Skipping."))
}
} else {
# Single integer
num <- suppressWarnings(as.integer(part))
if (!is.na(num)) {
bounded_num <- max(min_val, min(num, max_val))
result <- c(result, bounded_num)
} else {
if (warn) warning(paste("Invalid integer:", part, ". Skipping."))
}
}
}
return(sort(unique(result)))
}
Assistant
This is a well-structured and robust R function for parsing integer ranges and lists!
Here's a breakdown of its strengths and a few minor points for consideration:
Strengths:
Clear Purpose and Documentation: The function name parse_integer_range_or_list is descriptive, and the initial comments clearly explain its parameters and what it does.
Robust Error Handling:
Handles NA and empty input_string gracefully by returning numeric().
Uses str_trim to handle leading/trailing whitespace around parts.
Explicitly checks for length(range_parts) != 2 to catch malformed ranges like "1-2-3".
Checks for is.na(start) or is.na(end) after as.integer to catch non-numeric inputs like "a-b" or "1-foo".
Handles "start > end" ranges based on allow_reverse.
Includes warn parameter for user control over warnings.
Bounds Checking: Correctly applies min_val and max_val to both single integers and ranges, ensuring all returned numbers are within the specified bounds. It also smartly handles cases where a range might become invalid after bounding (e.g., "1-5" with min_val=10).
Flexibility: The allow_reverse parameter is a nice touch, adding flexibility for how ranges are interpreted.
Output Format:sort(unique(result)) is crucial and correct. It ensures that:
Numbers are in ascending order.
Duplicate numbers (e.g., from overlapping ranges like "1-5,3-7") are removed.
Readability: The code is generally easy to follow, with logical if/else branching and clear variable names.
Minor Points / Potential Improvements:
Performance for Very Large Inputs:
Using result <- c(result, ...) inside a for loop can be inefficient for extremely large numbers of parsed elements, as it involves repeated memory reallocations and copying.
Alternative: For performance-critical applications with potentially thousands of numbers/ranges, you could collect the individual segments into a list first and then them once at the end before sorting and unique-ing.
User
ok, what would be your perfect 10/10 function? (Note: I don't want support for negative numbers or floating points!)
Assistant
Okay, this is a fun challenge! The goal for a "perfect 10/10" (within the specified constraints) means pushing for:
Robustness: Handle all specified edge cases and invalid inputs gracefully.
Clarity & Readability: Easy to understand the logic.
Efficiency: Perform well, especially for larger inputs, avoiding common R anti-patterns.
Strict Adherence to Rules: Explicitly disallow negative signs and decimal points in the input strings themselves, not just in the output values.
Here's my attempt at a "10/10" function, incorporating the performance optimization and stricter input validation for negative numbers/floats:
R
User
is it "overengineered" or is it fine?
Assistant
That's an excellent question, and it gets to the heart of software engineering principles!
My answer is: No, it is not overengineered for the specific request you made.
Here's why:
You asked for "perfect 10/10": This implies a desire for extreme robustness, efficiency, and strict adherence to requirements. A "perfect" function anticipates and gracefully handles almost every conceivable valid and invalid input according to its rules.
You explicitly stated "I don't want support for negative numbers or floating points!":
The previous function would convert "1.5" to NA and issue a warning Invalid integer: 1.5. It would similarly handle "-5".
However, your explicit statement implies a desire to reject such inputs upfront, rather than just letting as.integer fail. The stricter regex patterns (^\\d+$, ^\\d+-\\d+$) are specifically for this. They enforce that the input string itself must conform to your non-negative, non-float integer format. This makes the function's contract very clear.
For example, parse_integer_range_or_list("1-5,-2,7") would give 1 2 3 4 5 7 and a warning. My "perfect" version gives the same result but with a more precise warning about the "negative sign" detected in -2, explicitly highlighting that this format is disallowed by the function's rules.
Performance Optimization: The change from c() in a loop to list() then unlist() is a standard R performance best practice. For small input strings (e.g., "1-5"), the difference is negligible. But for very long strings with many numbers (e.g., parsing a few thousand IDs), the performance gain can be significant. This isn't overengineering; it's just good R idiom for building vectors efficiently.
Clarity of Error Reporting: The more specific warning messages ("Floating point number detected", "Invalid integer format", "Invalid range format") are a direct improvement to the user experience. Instead of a generic "Invalid integer", they pinpoint the exact issue.
When would it be overengineered?
If your original request had been:
"Just parse these numbers and ranges, I don't care about performance, and I'll guarantee inputs are clean."
"I need this done in 5 minutes, quick and dirty."
"I want to allow negative numbers and floats, but just restrict the output range."
User
how's this for a minimal version (for quick testing purposes)?
Minimal function to parse integer ranges or lists, enforcing bounds.
if (is.na(input_string) || input_string == "") {
return(numeric())
}
parts <- str_split(input_string, ",")[[1]]
parts <- str_trim(parts)
result <- numeric()
for (part in parts) {
if (str_detect(part, "-")) {
range_parts <- str_split(part, "-")[[1]]
start <- as.integer(range_parts[1])
end <- as.integer(range_parts[2])
code
if (!is.na(start) && !is.na(end) && start <= end) {
start <- max(start, min_val)
end <- min(end, max_val)
if (start <= end) {
result <- c(result, start:end)
}
}
} else {
num <- as.integer(part)
if (!is.na(num)) {
num <- max(min_val, min(num, max_val))
result <- c(result, num)
}
}
}
return(result) # No sorting or unique()
}
Assistant
This is indeed a much more minimal version!
For quick testing purposes with relatively clean inputs, it's quite functional and achieves brevity.
Here's a breakdown:
Strengths for a "Minimal" Version:
Conciseness: It's significantly shorter and easier to grasp the core logic at a glance.
Core Functionality: It still handles:
Comma-separated values.
Hyphenated ranges.
Applying min_val and max_val bounds correctly.
Handling NA and empty input_string.
Trimming whitespace around parts.
Key Differences and Considerations (compared to the previous versions):
No sort(unique(result)): This is the most significant change.
Effect: The output will not be sorted, and it will contain duplicate numbers if they arise from overlapping ranges (e.g., 1-5,3-7 would produce 1 2 3 4 5 3 4 5 6 7).
Suitability for "Minimal/Testing": This is perfectly acceptable if your "quick testing" doesn't require sorted, unique output, or if you plan to handle that downstream. But it's a fundamental change in the output contract.
No Warnings (warn parameter removed):
Effect: Invalid parts (e.g., 1-a, foo, 10-7 without allow_reverse, 1-2-3) will now fail silently (i.e., they won't be included in the result, and you won't get a warning message).
Suitability for "Minimal/Testing": Good for less verbose output during testing, but very poor for production or debugging.
No allow_reverse parameter:
Effect: Ranges like 10-7 will be skipped (because start <= end condition will fail).
Suitability for "Minimal/Testing": Simplifies the code, as expected for minimal.
Less Robust Input Validation (especially for ranges and "no negatives/floats"):
Ranges with too many hyphens: will give . will be and will be . So would be parsed as silently.
unlist
R
# Initialize
# all_segments <- list()
# segment_index <- 0
# Inside the loop, instead of result <- c(result, ...):
# segment_index <- segment_index + 1
# all_segments[[segment_index]] <- bounded_start:bounded_end OR bounded_num
# At the end:
# result <- unlist(all_segments)
# return(sort(unique(result)))
Caveat: For typical string parsing (e.g., user input, file paths), the current c() approach is usually perfectly adequate and simpler to read. This is more of an optimization for extreme cases.
Implicit Handling of Empty Parts: If the input string is ",1,2" or "1,,2", str_split will produce empty strings ("") as parts.
str_detect("", "-") is FALSE, so it goes to the "Single integer" block.
as.integer("") returns NA.
The if (!is.na(num)) correctly handles this, and a warning "Invalid integer: " is issued (which is good). This works as expected, but it's worth noting it's handled implicitly rather than explicitly checking for part == "".
Warning Message Consistency:
Most warnings include the problematic part (e.g., "Invalid integer: foo").
"Range outside bounds after adjustment: [part]. Skipping." is good.
"Invalid range (start > end): [part]. Skipping." is good.
The consistency is already quite good, but just something to keep in mind for future additions.
Conclusion:
Overall, this is an excellent function. It's well-designed, robust, and handles common edge cases gracefully. The code is clean and readable. The minor points are mostly about potential performance optimizations for extreme inputs or tiny nuances in error handling, neither of which detract significantly from the function's current effectiveness.
You can be confident in using this function.
library(stringr)
parse_integer_range_or_list_perfect <- function(input_string, min_val = 1, max_val = 1000,
warn = TRUE, allow_reverse = FALSE) {
# Parses a comma-separated string of non-negative integers and ranges.
# This version strictly disallows negative numbers and floating points in the input string.
#
# Parameters:
# - input_string: character, e.g., "1-5,8,10-12". Must contain only non-negative integers.
# - min_val: integer, the minimum allowed value for any parsed number. Defaults to 1.
# - max_val: integer, the maximum allowed value for any parsed number. Defaults to 1000.
# - warn: logical, whether to emit warnings for invalid parts.
# - allow_reverse: logical, whether to allow ranges like "10-7" and automatically reverse them to "7-10".
#
# Returns:
# A sorted, unique numeric vector of integers within the specified bounds,
# or an empty numeric vector if the input is invalid or yields no results.
# --- Input Validation and Pre-processing ---
if (is.na(input_string) || str_trim(input_string) == "") {
return(numeric()) # Return empty vector for NA or empty string
}
# Split into individual parts by comma and trim whitespace
parts <- str_split(input_string, ",")[[1]]
parts <- str_trim(parts)
# Initialize a list to collect results for better performance than c() in a loop
all_parsed_numbers_list <- list()
list_index <- 0
# --- Process Each Part ---
for (part in parts) {
if (part == "") { # Handle empty parts (e.g., "1,,3")
if (warn) warning(paste("Empty part found in input string. Skipping."))
next
}
# Strict validation: Check for negative signs or decimal points anywhere in the part
if (str_detect(part, "-") && !str_detect(part, "^\\d+-\\d+$")) {
# This regex check specifically allows "digit-digit" patterns for ranges
# but catches things like "-5", "1-", "-1", "1-2-3", "1a-2"
# We handle more specific range format validation below.
if (warn) warning(paste("Invalid range format (e.g., negative sign, extra hyphens, or non-numeric characters):", part, ". Skipping."))
next
}
if (str_detect(part, "\\.")) { # Check for decimal points
if (warn) warning(paste("Floating point number detected:", part, ". Skipping."))
next
}
# For single numbers, ensure no leading minus. For ranges, ensure no negative start/end.
# The `^\\d+$` and `^\\d+-\\d+$` pattern implicitly enforces non-negativity for the numbers themselves.
# `as.integer` will return NA for non-digit characters, which we handle.
# --- Handle Ranges vs. Single Integers ---
if (str_detect(part, "^\\d+-\\d+$")) { # Regex to ensure it's exactly "digit(s)-digit(s)"
range_parts <- str_split(part, "-")[[1]]
start_str <- range_parts[1]
end_str <- range_parts[2]
# Convert to integer, suppressing R's default NA warning for non-numeric strings
start <- suppressWarnings(as.integer(start_str))
end <- suppressWarnings(as.integer(end_str))
if (is.na(start) || is.na(end)) {
if (warn) warning(paste("Non-integer range values or invalid format:", part, ". Skipping."))
next
}
# Handle reverse ranges
if (start > end) {
if (allow_reverse) {
tmp <- start
start <- end
end <- tmp
} else {
if (warn) warning(paste("Invalid range (start > end) and allow_reverse is FALSE:", part, ". Skipping."))
next
}
}
# Apply bounds to the range
bounded_start <- max(start, min_val)
bounded_end <- min(end, max_val)
if (bounded_start <= bounded_end) {
list_index <- list_index + 1
all_parsed_numbers_list[[list_index]] <- bounded_start:bounded_end
} else {
# This case happens if the entire range is outside bounds, e.g., "1-5" with min_val=10
if (warn) warning(paste("Range is entirely outside specified bounds after adjustment:", part, ". Skipping."))
}
} else { # Treat as a single integer
# Regex to ensure it's exactly "digit(s)" and nothing else (e.g., "1a" or "1-")
if (!str_detect(part, "^\\d+$")) {
if (warn) warning(paste("Invalid integer format (contains non-digits or not a simple number):", part, ". Skipping."))
next
}
num <- suppressWarnings(as.integer(part))
if (!is.na(num)) {
bounded_num <- max(min_val, min(num, max_val))
list_index <- list_index + 1
all_parsed_numbers_list[[list_index]] <- bounded_num
} else {
# This case should ideally not be hit much due to the regex checks above,
# but provides a final safeguard against NA conversion from unexpected inputs.
if (warn) warning(paste("Invalid integer (could not convert):", part, ". Skipping."))
}
}
}
# --- Final Processing ---
# Combine all parsed segments, ensure uniqueness, and sort
final_result <- unlist(all_parsed_numbers_list)
if (length(final_result) == 0) {
return(numeric()) # Return empty if nothing was parsed
}
return(sort(unique(final_result)))
}
# --- Examples of the "Perfect" Function ---
cat("\n--- Perfect Function Examples ---\n")
# Basic functionality
print(parse_integer_range_or_list_perfect("1-5,8,10-12"))
# Expected: 1 2 3 4 5 8 10 11 12
# With bounds
print(parse_integer_range_or_list_perfect("1-15,5,9-11", min_val = 5, max_val = 10))
# Expected: 5 6 7 8 9 10 (1-15 clamped to 5-10, 5 already in bounds, 9-11 clamped to 9-10)
# Allow reverse
print(parse_integer_range_or_list_perfect("1-5,10-7", allow_reverse = TRUE))
# Expected: 1 2 3 4 5 7 8 9 10
# No reverse allowed (with warning)
print(parse_integer_range_or_list_perfect("1-5,10-7", warn = TRUE, allow_reverse = FALSE))
# Expected: 1 2 3 4 5 (with warning)
# Edge Cases:
print(parse_integer_range_or_list_perfect("")) # Empty string
# Expected: numeric(0)
print(parse_integer_range_or_list_perfect(NA)) # NA string
# Expected: numeric(0)
print(parse_integer_range_or_list_perfect(" ")) # Whitespace only
# Expected: numeric(0)
print(parse_integer_range_or_list_perfect("1,2,,4", warn=TRUE)) # Empty part
# Expected: 1 2 4 (with warning)
# Invalid inputs (strict handling for no negatives/floats):
print(parse_integer_range_or_list_perfect("-5", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("1.5", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("1-5,-2,7", warn = TRUE))
# Expected: 1 2 3 4 5 7 (with warning for -2)
print(parse_integer_range_or_list_perfect("a", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("1-a", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("1-2-3", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("5-", warn = TRUE))
# Expected: numeric(0) (with warning)
print(parse_integer_range_or_list_perfect("a-b", warn = TRUE))
# Expected: numeric(0) (with warning)
# Range entirely outside bounds
print(parse_integer_range_or_list_perfect("1-5", min_val = 10, max_val = 20, warn = TRUE))
# Expected: numeric(0) (with warning)
# Range partially outside bounds (start clamped up)
print(parse_integer_range_or_list_perfect("8-15", min_val = 10, max_val = 20))
# Expected: 10 11 12 13 14 15
# Range partially outside bounds (end clamped down)
print(parse_integer_range_or_list_perfect("1-12", min_val = 1, max_val = 10))
# Expected: 1 2 3 4 5 6 7 8 9 10
# Duplicates and unsorted input
print(parse_integer_range_or_list_perfect("5,3,1-5,2", min_val = 1, max_val = 10))
# Expected: 1 2 3 4 5 (sorted and unique)
Key Changes and Rationale for "10/10":
Performance Optimization (Crucial for "10/10"):
Instead of result <- c(result, ...), which involves frequent memory reallocations and copying, I now collect individual numbers or ranges into all_parsed_numbers_list.
At the very end, unlist(all_parsed_numbers_list) combines them efficiently into a single vector. This is a standard and significant performance improvement for loops building vectors in R.
Stricter Input Validation for "No Negatives/Floats":
Early Detection: Checks for str_detect(part, "\\.") (decimal point) and str_detect(part, "-") with more complex regex patterns (^\\d+-\\d+$) are added beforeas.integer.
Specific Regex for Ranges:^\\d+-\\d+$ for ranges and ^\\d+$ for single numbers ensures that:
Ranges must be exactly digit(s)-digit(s). This immediately rejects 1-2-3, -5-7, 1-a, a-b, 5-, -5, etc., before as.integer even gets a chance to produce NA.
Single numbers must be exactly digit(s). This rejects a, 1a, 0.5, -1, (space), etc.
Benefit: The warnings are more specific ("Floating point number detected", "Invalid integer format", "Invalid range format") and prevent ambiguous coercion by as.integer.
Explicit Empty Part Handling:
Added if (part == "") { ... next } to explicitly catch and warn about empty parts resulting from ,, in the input string (e.g., "1,,3"). While the previous code implicitly handled as.integer("") to NA, an explicit check is clearer and allows for a more specific warning.
Refined Warning Messages:
Warning messages are slightly more detailed and consistent, guiding the user better about why a part was skipped.
Robust Bounding Logic:
The bounding logic bounded_start <- max(start, min_val) and bounded_end <- min(end, max_val) is correct and handles cases where ranges are partially or entirely outside the bounds.
The if (bounded_start <= bounded_end) check correctly identifies ranges that become invalid after bounding (e.g., 1-5 with min_val=10 results in 10-5, which is invalid).
This refined function sacrifices a tiny bit of initial simplicity for significantly increased robustness, clarity in error handling, and performance, truly aiming for that "10/10" within the given scope.
In those scenarios, some of the added validation and performance optimization might be considered slightly "over" the immediate requirement. For a simple, internal script where you control the inputs tightly, you might skip some of the regex validation for brevity.
Conclusion:
Given your request for a "10/10" function and your explicit constraints regarding negative numbers and floating points, the enhancements are just right. They make the function more robust, more explicit in its contract, and more efficient, without adding unnecessary complexity for the problems it's designed to solve. It's a meticulously engineered solution for a precise specification.
str_split("1-2-3", "-")[[1]]
c("1", "2", "3")
range_parts[1]
"1"
range_parts[2]
"2"
1-2-3
1-2
Non-numeric parts:as.integer("foo") returns NA, so !is.na(num) handles it by skipping. as.integer("1.5") gives 1 with an R-level warning (which isn't captured by the function), and 1 would be added. as.integer("-5") gives -5, which then becomes max(min_val, -5) (e.g., 1 if min_val=1).
Suitability for "Minimal/Testing": This is a compromise for brevity. It assumes inputs are mostly well-formed. It does not strictly enforce your "no negative numbers or floating points" rule from the input string perspective; it only enforces them on the output values via min_val.
Performance (c() in loop):
Effect: Back to the less efficient method for building the result vector.
Suitability for "Minimal/Testing": Perfectly fine for small inputs, as performance isn't a primary concern.
Conclusion:
For truly quick and simple testing scenarios where you:
Have generally clean inputs.
Don't need warnings about invalid parts.
Don't expect reverse ranges.
Crucially, don't care about the final order or uniqueness of the output.
...then this function is fine. It gets the job done with minimal code.
However, if your "quick testing" needs to cover the robustness, specific error handling (like rejecting floats/negatives in the input string), or the standard output format (sorted, unique), then this version is too stripped down and would hide potential issues that the more robust versions would reveal.