elm list comprehensions,检索列表的第n个元素

joh*_*ual 4 haskell list maybe elm

当我注意到Elm不支持列表推导时,我试图在Elm中模拟Rubik的立方体.在Haskell甚至是Python中,我会写一些类似于:

ghci> [2*c | c <- [1,2,3,4]]

[2,4,6,8]
Run Code Online (Sandbox Code Playgroud)

我在榆树找不到路.我必须写的实际列表理解是(在Haskell中):

ghci> let x = [0,1,3,2]
ghci> let y = [2,3,1,0]
ghci> [y !! fromIntegral c | c <- x]

[2,3,0,1]
Run Code Online (Sandbox Code Playgroud)

哪里fromIntegral :: (Integral a, Num b) => a -> b变成IntegerNum.

在Elm中,我尝试使用Arrays:

x = Array.fromList [0,1,3,2]
y = Array.fromList [2,3,1,0]
Array.get (Array.get 2 x) y
Run Code Online (Sandbox Code Playgroud)

我开始遇到Maybe类型的困难:

Expected Type: Maybe number
Actual Type: Int
Run Code Online (Sandbox Code Playgroud)

事实上,我不得不抬头看看它们是什么.我只是做了一些与列表有关的事情,而不是努力工作.

x = [0,1,3,2]
y = [2,3,1,0]

f n = head ( drop n x)
map f y
Run Code Online (Sandbox Code Playgroud)

我不知道这是否有效或正确,但它在我尝试的情况下有效.


我想我的两个主要问题是:

  • 榆树支持列表理解吗?(我想只是用map)
  • 如何绕过maybeArray示例中的类型?
  • 调用head ( drop n x)获取列表的第n个元素是否有效?

ja.*_*ja. 5

榆树不会也不会支持列表理解:https://github.com/elm-lang/Elm/issues/147

风格指南Evan所说的"喜欢地图,过滤和折叠",所以..使用`map:

map ((y !!).fromIntegral) x
Run Code Online (Sandbox Code Playgroud)

要么

map (\i-> y !! fromIntegral i) x
Run Code Online (Sandbox Code Playgroud)

评论者指出(!!)无效Elm(它是有效的Haskell).我们可以将其定义为:

(!!) a n = head (drop n a),总功能.

也许
(!!) a n = case (head (drop n a)) of Just x -> x Nothing -> crash "(!!) index error"