elm - 如何从 Elm Array 中过滤掉 "Nothing"值?

标签 elm maybe

我想定义以下函数:

compactAndConvertToList : Array (Maybe String) -> List String

此功能应删除所有 Nothing出现在给定数组中,并将其转换为 List .

我想出了下面的解决方案,但感觉有点脏。

有没有更好的方法来实现这一目标?
import Graphics.Element exposing (..)
import Array

model : Array.Array (Maybe String)
model = Array.fromList [ Just "Hello", Just "Stack", Nothing, Just "Overflow" ]


compactAndConvertToList : Array.Array (Maybe String) -> List String
compactAndConvertToList maybeStrings =
  maybeStrings
    |> Array.filter (\x -> x /= Nothing)
    |> Array.map (Maybe.withDefault "")
    |> Array.toList


main = 
  model
    |> compactAndConvertToList
    |> show

最佳答案

如果您的最终结果是一个列表,那么您最好将数组转换为列表,然后对其进行操作。

import Array 

compactAndConvertToList : Array.Array (Maybe String) -> List String
compactAndConvertToList = Array.toList >> List.filterMap identity

如果你对高阶函数不满意,你可以这样写:
compactAndConvertToList arr = List.filterMap identity (Array.toList arr)

我们获取我们的数组,将 toList 应用到它,然后用它应用 filterMap。过滤器映射采用一个生成可能的函数,并将其应用于列表中的每个元素,丢弃 Nothing案件。我们只是应用恒等函数,它丢弃了 Nothing已经存在的值。

一般来说,数组适合快速随机访问,但如果您多次遍历整个集合,列表往往会更快。但是,始终以清晰的方式开始,然后根据需要进行优化。

关于elm - 如何从 Elm Array 中过滤掉 "Nothing"值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33093359/

相关文章:

polymorphism - 在 Elm 中处理具有共享子结构的记录

elm - 在 elm-lang 的 case 表达式中,管道 `|` 运算符有什么作用?

node.js - 有没有一种方法可以编写一个内部带有 promise 的Maybe.map?

haskell - 在 case 语句中解析错误

haskell - 在Maybe中从(Just x)中提取x

haskell - 从 Haskell 中的 'a' 返回类型获取 'Maybe a' 值

types - 如何使用 Elm 自定义类型为 5 个骰子值建模?

types - 理解类型注解中的类型变量

elm - 在 Elm 中,有没有办法合并联合类型? (出于模块化目的)

haskell - Haskell 中 fromJust 的理由