diff --git a/config.json b/config.json index 3a3f97e..0864024 100644 --- a/config.json +++ b/config.json @@ -415,6 +415,14 @@ "prerequisites": [], "difficulty": 7 }, + { + "slug": "grep", + "name": "Grep", + "uuid": "eefaa478-9e56-40b5-a378-4af53008c71d", + "practices": [], + "prerequisites": [], + "difficulty": 8 + }, { "slug": "rest-api", "name": "REST API", diff --git a/exercises/practice/grep/.docs/instructions.md b/exercises/practice/grep/.docs/instructions.md new file mode 100644 index 0000000..004f28a --- /dev/null +++ b/exercises/practice/grep/.docs/instructions.md @@ -0,0 +1,27 @@ +# Instructions + +Search files for lines matching a search string and return all matching lines. + +The Unix [`grep`][grep] command searches files for lines that match a regular expression. +Your task is to implement a simplified `grep` command, which supports searching for fixed strings. + +The `grep` command takes three arguments: + +1. The string to search for. +2. Zero or more flags for customizing the command's behavior. +3. One or more files to search in. + +It then reads the contents of the specified files (in the order specified), finds the lines that contain the search string, and finally returns those lines in the order in which they were found. +When searching in multiple files, each matching line is prepended by the file name and a colon (':'). + +## Flags + +The `grep` command supports the following flags: + +- `-n` Prepend the line number and a colon (':') to each line in the output, placing the number after the filename (if present). +- `-l` Output only the names of the files that contain at least one matching line. +- `-i` Match using a case-insensitive comparison. +- `-v` Invert the program -- collect all lines that fail to match. +- `-x` Search only for lines where the search string matches the entire line. + +[grep]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html diff --git a/exercises/practice/grep/.meta/Example.roc b/exercises/practice/grep/.meta/Example.roc new file mode 100644 index 0000000..b262736 --- /dev/null +++ b/exercises/practice/grep/.meta/Example.roc @@ -0,0 +1,97 @@ +module [grep] + +import "iliad.txt" as iliad : Str +import "midsummer-night.txt" as midsummerNight : Str +import "paradise-lost.txt" as paradiseLost : Str + +grep : Str, List Str, List Str -> Result Str _ +grep = \pattern, flags, fileNames -> + config = parseFlags? flags + files = collectFiles? fileNames + displayFileNames = List.len files > 1 + List.joinMap files \file -> + when findMatches config pattern file.text is + [] -> [] + _ if config.displayFileNames -> [file.name] + matches -> + List.map matches \{ line, index } -> + lineNumber = + if config.displayLineNumbers then + "$(index + 1 |> Num.toStr):" + else + "" + fileName = + if displayFileNames then + "$(file.name):" + else + "" + "$(fileName)$(lineNumber)$(line)" + |> Str.joinWith "\n" + |> Ok + +findMatches : Config, Str, Str -> List { line : Str, index : U64 } +findMatches = \config, pattern, text -> + Str.split text "\n" + |> List.mapWithIndex \line, index -> + { line, index } + |> List.keepIf \{ line } -> + (lineToMatch, patternToMatch) = + if config.ignoreCase then + (toLower line, toLower pattern) + else + (line, pattern) + + matches = + if config.matchFullLines then + lineToMatch == patternToMatch + else + Str.contains lineToMatch patternToMatch + + # Using != is equivalent to xor which inverts `matches` + config.invertResults != matches + +toLower : Str -> Str +toLower = \str -> + Str.toUtf8 str + |> List.map \byte -> + if 'A' <= byte && byte <= 'Z' then + byte - 'A' + 'a' + else + byte + |> Str.fromUtf8 + |> Result.withDefault "" + +Config : { + displayLineNumbers : Bool, + displayFileNames : Bool, + ignoreCase : Bool, + matchFullLines : Bool, + invertResults : Bool, +} + +parseFlags : List Str -> Result Config _ +parseFlags = \flags -> + defaultConfig = { + displayLineNumbers: Bool.false, + displayFileNames: Bool.false, + ignoreCase: Bool.false, + matchFullLines: Bool.false, + invertResults: Bool.false, + } + List.walkTry flags defaultConfig \config, flag -> + when flag is + "-l" -> Ok { config & displayFileNames: Bool.true } + "-n" -> Ok { config & displayLineNumbers: Bool.true } + "-i" -> Ok { config & ignoreCase: Bool.true } + "-x" -> Ok { config & matchFullLines: Bool.true } + "-v" -> Ok { config & invertResults: Bool.true } + _ -> Err (UnknownFlag flag) + +collectFiles : List Str -> Result (List { name : Str, text : Str }) _ +collectFiles = \names -> + List.mapTry names \name -> + when name is + "midsummer-night.txt" -> Ok { name: "midsummer-night.txt", text: midsummerNight } + "iliad.txt" -> Ok { name: "iliad.txt", text: iliad } + "paradise-lost.txt" -> Ok { name: "paradise-lost.txt", text: paradiseLost } + _ -> Err (FileNotFound name) diff --git a/exercises/practice/grep/.meta/config.json b/exercises/practice/grep/.meta/config.json new file mode 100644 index 0000000..5f54353 --- /dev/null +++ b/exercises/practice/grep/.meta/config.json @@ -0,0 +1,19 @@ +{ + "authors": [ + "isaacvando" + ], + "files": { + "solution": [ + "Grep.roc" + ], + "test": [ + "grep-test.roc" + ], + "example": [ + ".meta/Example.roc" + ] + }, + "blurb": "Search a file for lines matching a regular expression pattern. Return the line number and contents of each matching line.", + "source": "Conversation with Nate Foster.", + "source_url": "https://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf" +} diff --git a/exercises/practice/grep/.meta/template.j2 b/exercises/practice/grep/.meta/template.j2 new file mode 100644 index 0000000..6e9bd7c --- /dev/null +++ b/exercises/practice/grep/.meta/template.j2 @@ -0,0 +1,15 @@ +{%- import "generator_macros.j2" as macros with context -%} +{{ macros.canonical_ref() }} +{{ macros.header() }} + +import {{ exercise | to_pascal }} exposing [grep] + +{% for case in cases -%} +{% for innerCase in case["cases"] -%} +# {{ case["description"] }} - {{ innerCase["description"] }} +expect + result = {{ innerCase["property"] | to_camel }} {{ innerCase["input"]["pattern"] | to_roc }} {{ innerCase["input"]["flags"] | to_roc }} {{ innerCase["input"]["files"] | to_roc }} + result == Ok {{ innerCase["expected"] | join('\n') | to_roc_multiline_string | indent(8) }} + +{% endfor %} +{% endfor %} diff --git a/exercises/practice/grep/.meta/tests.toml b/exercises/practice/grep/.meta/tests.toml new file mode 100644 index 0000000..04c51e7 --- /dev/null +++ b/exercises/practice/grep/.meta/tests.toml @@ -0,0 +1,85 @@ +# This is an auto-generated file. +# +# Regenerating this file via `configlet sync` will: +# - Recreate every `description` key/value pair +# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications +# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion) +# - Preserve any other key/value pair +# +# As user-added comments (using the # character) will be removed when this file +# is regenerated, comments can be added via a `comment` key. + +[9049fdfd-53a7-4480-a390-375203837d09] +description = "Test grepping a single file -> One file, one match, no flags" + +[76519cce-98e3-46cd-b287-aac31b1d77d6] +description = "Test grepping a single file -> One file, one match, print line numbers flag" + +[af0b6d3c-e0e8-475e-a112-c0fc10a1eb30] +description = "Test grepping a single file -> One file, one match, case-insensitive flag" + +[ff7af839-d1b8-4856-a53e-99283579b672] +description = "Test grepping a single file -> One file, one match, print file names flag" + +[8625238a-720c-4a16-81f2-924ec8e222cb] +description = "Test grepping a single file -> One file, one match, match entire lines flag" + +[2a6266b3-a60f-475c-a5f5-f5008a717d3e] +description = "Test grepping a single file -> One file, one match, multiple flags" + +[842222da-32e8-4646-89df-0d38220f77a1] +description = "Test grepping a single file -> One file, several matches, no flags" + +[4d84f45f-a1d8-4c2e-a00e-0b292233828c] +description = "Test grepping a single file -> One file, several matches, print line numbers flag" + +[0a483b66-315b-45f5-bc85-3ce353a22539] +description = "Test grepping a single file -> One file, several matches, match entire lines flag" + +[3d2ca86a-edd7-494c-8938-8eeed1c61cfa] +description = "Test grepping a single file -> One file, several matches, case-insensitive flag" + +[1f52001f-f224-4521-9456-11120cad4432] +description = "Test grepping a single file -> One file, several matches, inverted flag" + +[7a6ede7f-7dd5-4364-8bf8-0697c53a09fe] +description = "Test grepping a single file -> One file, no matches, various flags" + +[3d3dfc23-8f2a-4e34-abd6-7b7d140291dc] +description = "Test grepping a single file -> One file, one match, file flag takes precedence over line flag" + +[87b21b24-b788-4d6e-a68b-7afe9ca141fe] +description = "Test grepping a single file -> One file, several matches, inverted and match entire lines flags" + +[ba496a23-6149-41c6-a027-28064ed533e5] +description = "Test grepping multiples files at once -> Multiple files, one match, no flags" + +[4539bd36-6daa-4bc3-8e45-051f69f5aa95] +description = "Test grepping multiples files at once -> Multiple files, several matches, no flags" + +[9fb4cc67-78e2-4761-8e6b-a4b57aba1938] +description = "Test grepping multiples files at once -> Multiple files, several matches, print line numbers flag" + +[aeee1ef3-93c7-4cd5-af10-876f8c9ccc73] +description = "Test grepping multiples files at once -> Multiple files, one match, print file names flag" + +[d69f3606-7d15-4ddf-89ae-01df198e6b6c] +description = "Test grepping multiples files at once -> Multiple files, several matches, case-insensitive flag" + +[82ef739d-6701-4086-b911-007d1a3deb21] +description = "Test grepping multiples files at once -> Multiple files, several matches, inverted flag" + +[77b2eb07-2921-4ea0-8971-7636b44f5d29] +description = "Test grepping multiples files at once -> Multiple files, one match, match entire lines flag" + +[e53a2842-55bb-4078-9bb5-04ac38929989] +description = "Test grepping multiples files at once -> Multiple files, one match, multiple flags" + +[9c4f7f9a-a555-4e32-bb06-4b8f8869b2cb] +description = "Test grepping multiples files at once -> Multiple files, no matches, various flags" + +[ba5a540d-bffd-481b-bd0c-d9a30f225e01] +description = "Test grepping multiples files at once -> Multiple files, several matches, file flag takes precedence over line number flag" + +[ff406330-2f0b-4b17-9ee4-4b71c31dd6d2] +description = "Test grepping multiples files at once -> Multiple files, several matches, inverted and match entire lines flags" diff --git a/exercises/practice/grep/Grep.roc b/exercises/practice/grep/Grep.roc new file mode 100644 index 0000000..1b5ec3c --- /dev/null +++ b/exercises/practice/grep/Grep.roc @@ -0,0 +1,9 @@ +module [grep] + +import "iliad.txt" as iliad : Str +import "midsummer-night.txt" as midsummerNight : Str +import "paradise-lost.txt" as paradiseLost : Str + +grep : Str, List Str, List Str -> Result Str _ +grep = \pattern, flags, files -> + crash "Please implement 'grep'" diff --git a/exercises/practice/grep/grep-test.roc b/exercises/practice/grep/grep-test.roc new file mode 100644 index 0000000..d2a5794 --- /dev/null +++ b/exercises/practice/grep/grep-test.roc @@ -0,0 +1,232 @@ +# These tests are auto-generated with test data from: +# https://github.com/exercism/problem-specifications/tree/main/exercises/grep/canonical-data.json +# File last updated on 2024-09-15 +app [main] { + pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.15.0/SlwdbJ-3GR7uBWQo6zlmYWNYOxnvo8r6YABXD-45UOw.tar.br" +} + +main = + Task.ok {} + +import Grep exposing [grep] + +# Test grepping a single file - One file, one match, no flags +expect + result = grep "Agamemnon" [] ["iliad.txt"] + result == Ok "Of Atreus, Agamemnon, King of men." + +# Test grepping a single file - One file, one match, print line numbers flag +expect + result = grep "Forbidden" ["-n"] ["paradise-lost.txt"] + result == Ok "2:Of that Forbidden Tree, whose mortal tast" + +# Test grepping a single file - One file, one match, case-insensitive flag +expect + result = grep "FORBIDDEN" ["-i"] ["paradise-lost.txt"] + result == Ok "Of that Forbidden Tree, whose mortal tast" + +# Test grepping a single file - One file, one match, print file names flag +expect + result = grep "Forbidden" ["-l"] ["paradise-lost.txt"] + result == Ok "paradise-lost.txt" + +# Test grepping a single file - One file, one match, match entire lines flag +expect + result = grep "With loss of Eden, till one greater Man" ["-x"] ["paradise-lost.txt"] + result == Ok "With loss of Eden, till one greater Man" + +# Test grepping a single file - One file, one match, multiple flags +expect + result = grep "OF ATREUS, Agamemnon, KIng of MEN." ["-n", "-i", "-x"] ["iliad.txt"] + result == Ok "9:Of Atreus, Agamemnon, King of men." + +# Test grepping a single file - One file, several matches, no flags +expect + result = grep "may" [] ["midsummer-night.txt"] + result == Ok + """ + Nor how it may concern my modesty, + But I beseech your grace that I may know + The worst that may befall me in this case, + """ + +# Test grepping a single file - One file, several matches, print line numbers flag +expect + result = grep "may" ["-n"] ["midsummer-night.txt"] + result == Ok + """ + 3:Nor how it may concern my modesty, + 5:But I beseech your grace that I may know + 6:The worst that may befall me in this case, + """ + +# Test grepping a single file - One file, several matches, match entire lines flag +expect + result = grep "may" ["-x"] ["midsummer-night.txt"] + result == Ok "" + +# Test grepping a single file - One file, several matches, case-insensitive flag +expect + result = grep "ACHILLES" ["-i"] ["iliad.txt"] + result == Ok + """ + Achilles sing, O Goddess! Peleus' son; + The noble Chief Achilles from the son + """ + +# Test grepping a single file - One file, several matches, inverted flag +expect + result = grep "Of" ["-v"] ["paradise-lost.txt"] + result == Ok + """ + Brought Death into the World, and all our woe, + With loss of Eden, till one greater Man + Restore us, and regain the blissful Seat, + Sing Heav'nly Muse, that on the secret top + That Shepherd, who first taught the chosen Seed + """ + +# Test grepping a single file - One file, no matches, various flags +expect + result = grep "Gandalf" ["-n", "-l", "-x", "-i"] ["iliad.txt"] + result == Ok "" + +# Test grepping a single file - One file, one match, file flag takes precedence over line flag +expect + result = grep "ten" ["-n", "-l"] ["iliad.txt"] + result == Ok "iliad.txt" + +# Test grepping a single file - One file, several matches, inverted and match entire lines flags +expect + result = grep "Illustrious into Ades premature," ["-x", "-v"] ["iliad.txt"] + result == Ok + """ + Achilles sing, O Goddess! Peleus' son; + His wrath pernicious, who ten thousand woes + Caused to Achaia's host, sent many a soul + And Heroes gave (so stood the will of Jove) + To dogs and to all ravening fowls a prey, + When fierce dispute had separated once + The noble Chief Achilles from the son + Of Atreus, Agamemnon, King of men. + """ + + +# Test grepping multiples files at once - Multiple files, one match, no flags +expect + result = grep "Agamemnon" [] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok "iliad.txt:Of Atreus, Agamemnon, King of men." + +# Test grepping multiples files at once - Multiple files, several matches, no flags +expect + result = grep "may" [] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + midsummer-night.txt:Nor how it may concern my modesty, + midsummer-night.txt:But I beseech your grace that I may know + midsummer-night.txt:The worst that may befall me in this case, + """ + +# Test grepping multiples files at once - Multiple files, several matches, print line numbers flag +expect + result = grep "that" ["-n"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + midsummer-night.txt:5:But I beseech your grace that I may know + midsummer-night.txt:6:The worst that may befall me in this case, + paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast + paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top + """ + +# Test grepping multiples files at once - Multiple files, one match, print file names flag +expect + result = grep "who" ["-l"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + iliad.txt + paradise-lost.txt + """ + +# Test grepping multiples files at once - Multiple files, several matches, case-insensitive flag +expect + result = grep "TO" ["-i"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + iliad.txt:Caused to Achaia's host, sent many a soul + iliad.txt:Illustrious into Ades premature, + iliad.txt:And Heroes gave (so stood the will of Jove) + iliad.txt:To dogs and to all ravening fowls a prey, + midsummer-night.txt:I do entreat your grace to pardon me. + midsummer-night.txt:In such a presence here to plead my thoughts; + midsummer-night.txt:If I refuse to wed Demetrius. + paradise-lost.txt:Brought Death into the World, and all our woe, + paradise-lost.txt:Restore us, and regain the blissful Seat, + paradise-lost.txt:Sing Heav'nly Muse, that on the secret top + """ + +# Test grepping multiples files at once - Multiple files, several matches, inverted flag +expect + result = grep "a" ["-v"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + iliad.txt:Achilles sing, O Goddess! Peleus' son; + iliad.txt:The noble Chief Achilles from the son + midsummer-night.txt:If I refuse to wed Demetrius. + """ + +# Test grepping multiples files at once - Multiple files, one match, match entire lines flag +expect + result = grep "But I beseech your grace that I may know" ["-x"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok "midsummer-night.txt:But I beseech your grace that I may know" + +# Test grepping multiples files at once - Multiple files, one match, multiple flags +expect + result = grep "WITH LOSS OF EDEN, TILL ONE GREATER MAN" ["-n", "-i", "-x"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok "paradise-lost.txt:4:With loss of Eden, till one greater Man" + +# Test grepping multiples files at once - Multiple files, no matches, various flags +expect + result = grep "Frodo" ["-n", "-l", "-x", "-i"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok "" + +# Test grepping multiples files at once - Multiple files, several matches, file flag takes precedence over line number flag +expect + result = grep "who" ["-n", "-l"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + iliad.txt + paradise-lost.txt + """ + +# Test grepping multiples files at once - Multiple files, several matches, inverted and match entire lines flags +expect + result = grep "Illustrious into Ades premature," ["-x", "-v"] ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"] + result == Ok + """ + iliad.txt:Achilles sing, O Goddess! Peleus' son; + iliad.txt:His wrath pernicious, who ten thousand woes + iliad.txt:Caused to Achaia's host, sent many a soul + iliad.txt:And Heroes gave (so stood the will of Jove) + iliad.txt:To dogs and to all ravening fowls a prey, + iliad.txt:When fierce dispute had separated once + iliad.txt:The noble Chief Achilles from the son + iliad.txt:Of Atreus, Agamemnon, King of men. + midsummer-night.txt:I do entreat your grace to pardon me. + midsummer-night.txt:I know not by what power I am made bold, + midsummer-night.txt:Nor how it may concern my modesty, + midsummer-night.txt:In such a presence here to plead my thoughts; + midsummer-night.txt:But I beseech your grace that I may know + midsummer-night.txt:The worst that may befall me in this case, + midsummer-night.txt:If I refuse to wed Demetrius. + paradise-lost.txt:Of Mans First Disobedience, and the Fruit + paradise-lost.txt:Of that Forbidden Tree, whose mortal tast + paradise-lost.txt:Brought Death into the World, and all our woe, + paradise-lost.txt:With loss of Eden, till one greater Man + paradise-lost.txt:Restore us, and regain the blissful Seat, + paradise-lost.txt:Sing Heav'nly Muse, that on the secret top + paradise-lost.txt:Of Oreb, or of Sinai, didst inspire + paradise-lost.txt:That Shepherd, who first taught the chosen Seed + """ + + + diff --git a/exercises/practice/grep/iliad.txt b/exercises/practice/grep/iliad.txt new file mode 100644 index 0000000..960ec6b --- /dev/null +++ b/exercises/practice/grep/iliad.txt @@ -0,0 +1,9 @@ +Achilles sing, O Goddess! Peleus' son; +His wrath pernicious, who ten thousand woes +Caused to Achaia's host, sent many a soul +Illustrious into Ades premature, +And Heroes gave (so stood the will of Jove) +To dogs and to all ravening fowls a prey, +When fierce dispute had separated once +The noble Chief Achilles from the son +Of Atreus, Agamemnon, King of men. \ No newline at end of file diff --git a/exercises/practice/grep/midsummer-night.txt b/exercises/practice/grep/midsummer-night.txt new file mode 100644 index 0000000..2c57705 --- /dev/null +++ b/exercises/practice/grep/midsummer-night.txt @@ -0,0 +1,7 @@ +I do entreat your grace to pardon me. +I know not by what power I am made bold, +Nor how it may concern my modesty, +In such a presence here to plead my thoughts; +But I beseech your grace that I may know +The worst that may befall me in this case, +If I refuse to wed Demetrius. \ No newline at end of file diff --git a/exercises/practice/grep/paradise-lost.txt b/exercises/practice/grep/paradise-lost.txt new file mode 100644 index 0000000..2bdc17b --- /dev/null +++ b/exercises/practice/grep/paradise-lost.txt @@ -0,0 +1,8 @@ +Of Mans First Disobedience, and the Fruit +Of that Forbidden Tree, whose mortal tast +Brought Death into the World, and all our woe, +With loss of Eden, till one greater Man +Restore us, and regain the blissful Seat, +Sing Heav'nly Muse, that on the secret top +Of Oreb, or of Sinai, didst inspire +That Shepherd, who first taught the chosen Seed \ No newline at end of file