如何在 PureScript 列表中显示每个项目

How to show each item in a PureScript List

纯脚本列表中有foreach方法吗? foreach 方法采用列表中的每个项目和 returns 一个单元。

这是打印列表中每一项的好方法。

编辑:我正在尝试下面建议的遍历方法,但出现错误

import Data.Traversable (traverse)
removeDuplicate :: AddressBook -> AddressBook 
removeDuplicate = nubBy (\a b -> a.firstName == b.firstName && a.lastName == b.lastName)    
let dedup = removeDuplicate addressBook  
traverse (\a -> log (showEntry a)) dedup

Compiling Main
Error found:
in module Main
at src/Main.purs line 73, column 3 - line 73, column 49

  Could not match type

    List Unit

  with type

    Unit


while trying to match type Eff
                             ( console :: CONSOLE
                             | t1
                             )
                             t2
  with type Eff
              ( console :: CONSOLE
              | e0
              )
              Unit
while checking that expression (discard (logShow ((...) addressBook))) (\__unused ->
                                                                          (discard (...)) (\__unused ->
                                                                                             ...
                                                                                          )
                                                                       )
  has type Eff
             ( console :: CONSOLE
             | e0
             )
             Unit
in value declaration main

where e0 is a rigid type variable
        bound at line 63, column 8 - line 78, column 38
      t2 is an unknown type
      t1 is an unknown type

See https://github.com/purescript/documentation/blob/master/errors/TypesDoNotUnify.md for more information,
or to contribute content related to this error.

当然,它存在。它被称为map。您当然可以使用它来将函数 a -> unit 应用于数组的每个元素:

arr = [1, 2, 3]
map (\a -> unit) arr

但是,您 post 的第二部分 - “打印列表中每个项目的好方法” - 是不正确的。接受一个项目和 returns 一个单元的函数肯定不能打印任何东西。 PureScript 是一种纯语言,纯函数不能在其中产生效果。

要打印某些东西,您需要一个 returns 一个 EffAff 的函数,例如 log. To apply such function over an array (or another container), use traverse:

arr = [1, 2, 3]
traverse (\a -> log $ show a) arr

traverse 将函数应用于每个元素并按元素顺序执行结果效果。

您可以使用 for_,它允许您对 Foldable 的每个项目执行 "applicative action"(ListArrayFoldable 实例)并忽略此操作结果:

module Main where

import Control.Monad.Eff.Console (logShow)
import Data.Foldable (for_)
import Prelude

main = do
  -- I'm using an Array here for simplicity, but the same goes for List
  let l = [1, 2, 3, 4]

  for_ l \i → logShow i

List 也有 Show 实例 (second on the instances list)(还有数组 - last on the instances list) 因此如果它们包含具有 Show 实例的类型的值,您可以直接使用 logShow 打印它们。