如何使用Elm中的循环构建列表?

Cod*_*rer 3 loops elm

假设我有两个列表,列表letters,包含字母AF和列表nums,包含数字1-6.

在Elm中,我如何以编程方式创建包含所有可能组合的列表(即A1,C6,F3,D2等)?

这只是为了代码优雅的目的,硬编码每个可能的组合将是等价的.

在JavaScript中,它将表示为......

const nums = [1,2,3,4,5,6];
const letters = [`a`,`b`,`c`,`d`,`e`,`f`];

const combineLists = (a,b)=>{
  const newList = [];
  a.forEach(aEl=>{
    b.forEach(bEl=>{
      newList.push(aEl + bEl);
    })
  })
  return newList;
}
          
console.log(combineLists(letters,nums));
Run Code Online (Sandbox Code Playgroud)

你会如何combineLists在榆树中写出一个等效函数?

Sim*_*n H 9

这是我的建议,我认为这是最简洁的

module Main exposing (..)

import Html exposing (..)


nums : List Int
nums =
    [ 1, 2, 3, 4, 5, 6 ]


letters : List String
letters =
    [ "a", "b", "c", "d", "e", "f" ]


main =
    nums
        |> List.map toString
        |> List.concatMap (\n -> List.map (String.append n) letters)
        -- or in point free style
        -- |> List.concatMap (String.append >> flip List.map letters)
        |> toString
        |> text
Run Code Online (Sandbox Code Playgroud)

点自由风格似乎没有像在Haskell中那样在Elm中具有相同的自豪感,但是为了完整性而包含它并且是我编写代码的方式