纯脚本列表中是否有 foreach 方法?foreach 方法获取列表的每个项目并返回一个单位。
它是打印列表中每个项目的好方法。
编辑:我正在尝试下面建议的 traverse 方法,但出现错误
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.
Run Code Online (Sandbox Code Playgroud)
当然,它存在。它被称为map。您当然可以使用它来将函数a -> unit应用于数组的每个元素:
arr = [1, 2, 3]
map (\a -> unit) arr
Run Code Online (Sandbox Code Playgroud)
但是,您帖子的第二部分-“打印列表中的每个项目的好方法”- 不正确。一个接受一个项目并返回一个单位的函数当然不能打印任何东西。PureScript 是一种纯语言,纯函数不能在其中起作用。
要打印某些内容,您需要一个返回 anEff或 an的函数Aff,例如log. 要将此类函数应用于数组(或另一个容器),请使用traverse:
arr = [1, 2, 3]
traverse (\a -> log $ show a) arr
Run Code Online (Sandbox Code Playgroud)
traverse 将函数应用于每个元素并按照元素的顺序执行产生的效果。
您可以使用for_which 允许您对Foldable(List并且Array有Foldable实例) 的每个项目执行“应用操作”并忽略此操作结果:
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
Run Code Online (Sandbox Code Playgroud)
List还有Show实例(实例列表中的第二个)(以及 Array 也是
实例列表中的最后一个),因此logShow如果它们包含具有Show实例的类型的值,您可以直接使用它们打印它们。
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |