如何遍历PureScript List元素?是否有类似foreach的方法?调用traverse报错
Great question! Let's break this down step by step—covering the "foreach-like" methods you're looking for, plus why your traverse attempt might have failed.
1. Yes, PureScript has "foreach" equivalents for List
If you want to iterate over a List, run a side effect (like printing) for each element, and return Unit (no useful result), you have a few solid options:
Option 1: for_ (most universal)
for_ lives in Control.Monad and works with any Foldable type (not just List—think Array, Maybe, etc.). It's essentially a flipped version of traverse_, which makes the code read more naturally (like a "for each" loop).
Example usage for printing:
import Data.List (List, fromFoldable) import Control.Monad (for_) import Effect.Console (log) main :: Effect Unit main = do let numbers = fromFoldable [1, 2, 3] :: List Int for_ numbers \num -> log $ "Number: " <> show num
Option 2: forEach (List-specific)
If you only need to work with List, there's a dedicated forEach function in Data.List. It does exactly what you'd expect: takes a List and a function that runs a side effect for each element.
Example:
import Data.List (List, fromFoldable, forEach) import Effect.Console (log) main :: Effect Unit main = do let fruits = fromFoldable ["apple", "banana", "cherry"] :: List String forEach fruits \fruit -> log $ "Fruit: " <> fruit
2. Why your traverse attempt failed
traverse is a powerful function, but it's not meant for side effects where you don't care about the result. Here's the key difference:
traverse: Takes a function that returns anApplicative f a, runs it over each element, and collects all the results into anf (List a). So if you usetraverse log myList, you'd get anEffect (List Unit)—a computation that returns a List ofUnitvalues.traverse_(note the trailing underscore): Does the same iteration and side effects, but discards all results, returning justf Unit(which is exactly what you want for printing).
If you tried using traverse directly, you probably got a type error because your code expected an Effect Unit but got an Effect (List Unit) instead. The fix is simple: swap traverse for traverse_ (or use for_ as we saw earlier).
Example of the corrected traverse_ usage:
import Data.List (List, fromFoldable) import Control.Monad (traverse_) import Effect.Console (log) main :: Effect Unit main = do let items = fromFoldable [True, False, True] :: List Boolean traverse_ (\item -> log $ "Boolean: " <> show item) items
Quick Recap
- Use
for_for a universal, readable "foreach" style loop (works with all Foldables) - Use
forEachif you only need to target List specifically - Avoid
traversefor side-effect-only iteration—usetraverse_instead to avoid type errors and unnecessary result collection
内容的提问来源于stack exchange,提问作者Knows Not Much

