Stream: beginners

Topic: ✔ Searching for folders named 'foo' within a Path


view this post on Zulip Stuart Hinson (Sep 27 2024 at 20:47):

I've been struggling longer than I'd like to admit writing a function to search a starting folder for any nested folders named 'foo'. Specifically, nested Tasks are tripping me up. If anyone's up for writing a quick implementation I'd love to study it

view this post on Zulip Ian McLerran (Sep 27 2024 at 21:07):

I’d be happy to write one up when I get home here. I think you should be able to adapt this function which recursively prints a directory tree to do what you’re trying to. Just change the accumulator.

https://github.com/imclerran/roc-openrouter/blob/main/package/Toolkit/FileSystem.roc#L89-L109

view this post on Zulip Ian McLerran (Sep 27 2024 at 21:54):

This should do the trick:

findDirs : Str, Path -> Task (List Path) _
findDirs = \query, searchPath ->
    findDirsHelper [] (Path.listDir! searchPath) query

findDirsHelper : List Path, List Path, Str -> Task (List Path) _
findDirsHelper = \found, dirContents, query ->
    appendMatch = \acc, path ->
        when Path.display path |> Str.splitLast "/" is
            Ok { after: dirname } if dirname == query -> List.append acc path
            _ -> acc

    when dirContents is
        [path, .. as remainder] ->
            if Path.isDir! path then
                appendMatch found path
                |> findDirsHelper! (Path.listDir! path) query
                |> findDirsHelper remainder query
            else
                findDirsHelper found remainder query

        [] -> Task.ok found

view this post on Zulip Stuart Hinson (Sep 27 2024 at 23:05):

Thank you! That's very clear and exactly what I needed

view this post on Zulip Notification Bot (Sep 27 2024 at 23:05):

Stuart Hinson has marked this topic as resolved.


Last updated: Jul 06 2025 at 12:14 UTC