News for hackers. Stuff that matters.

itsmeknt

Thanks! I have updated my post to use your code. It is indeed much nicer. And yes, I don't write much FP.

I just improved the comprehension code as well using the same idea as your code, eliminating an entire list!

True! Good point on the restructuring, I haven't thought about it in that way.

I think I like the second approach because the loop behavior seems clearest, which helps me analyze the time complexity or when I want to skim the code quickly.

A syntax like something below would be perfect for me if it existed:

  var favoriteFoodsOfFurryPetsOfFamousAuthorsOfLongChineseBooksAboutHistory = books[i].author.pets[j].favoriteFood.distinct()
    where i = pagecount > 100,
              language == "Chinese",
              subject == "History",
              author.mentions > 10_000
    where j = is_furry == True
I tried scaling up the original into an intentionally convoluted nonsensical problem to see how a more complicated solution would look like for each approach. Do these look right? And which seems the most readable?

  # Functional approach
  
  var favoriteFoodsOfFurryPetsOfFamousAuthorsOfLongChineseBooksAboutHistory = books
    .filter(book => book.pageCount > 100 and book.language == "Chinese" and book.subject == "History")
    .map(book => book.author)
    .filter(author => author.mentions > 10_000)
    .map(author => author.pets)
    .reduce(acc, curr => acc.append(curr), [])
    .filter(pet => pet.is_furry == True)
    .map(pet => pet.favoriteFood)
    .distinct()
  
  # Procedural approach
  
  var favoriteFoodsOfFurryPetsOfFamousAuthorsOfLongChineseBooksAboutHistory = set()
  for book in books:
    if len(book.pageCount > 100) and book.language == "Chinese" and book.subject == "History" and book.author.mentions > 10_000:
      for pet in book.author.pets:
        if pet.is_furry:
          favoriteFoodsOfFurryPetsOfFamousAuthorsOfLongChineseBooksAboutHistory.add(pet.favoriteFood)

  # Comprehension approach
  
  var favoriteFoodsOfFurryPetsOfFamousAuthorsOfLongChineseBooksAboutHistory = {
    pet.favoriteFood for pet in
      pets for pets in 
        [author.pets for author in 
          [book.author for book in
            books if len(book.pageCount > 100) and book.language == "Chinese" and book.subject == "History"]
        if author.mentions > 10_000]

    if pet.is_furry
  }
FWIW, for more complex problems, I think the second one is the most readable.
Re:The secrets I found investigating corrupt Winamp skins on Thursday July 25, 2024 @01:28AM (#41065008)
When a new island is formed, usually it is first inhabited by algae and moss. As the ecosystem matures, plants, birds, insects, and all sorts of organisms populate it. You can still usually find the early algae and moss. They are just harder to spot due to the thriving and abundant ecosystem.

I think the Internet is a lot like that.