수색…


비고

List ( 링크 된 목록 )은 순차적 액세스 에서 빛난다.

  • 첫 번째 요소에 액세스
  • 목록 앞쪽에 붙어있는
  • 목록 앞에서 삭제

반면에 랜덤 액세스 (예 : n 번째 요소 가져 오기) 및 역순으로 트래버스하는 것은 이상적이지 않으며 Array 데이터 구조를 사용하면 더 나은 행운 (및 성능)을 얻을 수 있습니다.

범위로 목록 만들기

0.18.0

0.18.0 이전에는 다음과 같은 범위를 만들 수 있습니다.

> range = [1..5]
[1,2,3,4,5] : List number
>
> negative = [-5..3]
[-5,-4,-3,-2,-1,0,1,2,3] : List number
0.18.0

0.18.0 에서 [1..5] 문법 이 삭제되었습니다 .

> range = List.range 1 5
[1,2,3,4,5] : List number
>
> negative = List.range -5 3
[-5,-4,-3,-2,-1,0,1,2,3] : List number

이 구문으로 작성된 범위는 항상 포함 되며 단계 는 항상 1 입니다.

목록 만들기

> listOfNumbers = [1,4,99]
[1,4,99] : List number
>
> listOfStrings = ["Hello","World"]
["Hello","World"] : List String
>
> emptyList = []   -- can be anything, we don't know yet
[] : List a
>

후드에서 List ( linked list )는 :: 함수 ( "cons"라고 함)에 의해 구성됩니다.이 인수는 머리로 알려진 요소와 머리가 앞에 붙는 (빈 상태 일 가능성이있는) 목록이라는 두 개의 인수를 취합니다.

> withoutSyntaxSugar = 1 :: []
[1] : List number
>
> longerOne = 1 :: 2 :: 3 :: []
[1,2,3] : List number
>
> nonemptyTail = 1 :: [2]
[1,2] : List number
>

List 에는 한 가지 유형의 값만 사용할 수 있으므로 [1,"abc"] 와 같은 것은 불가능합니다. 이것을 원한다면 튜플을 사용하십시오.

> notAllowed = [1,"abc"]
==================================== ERRORS ====================================

-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The 1st and 2nd elements are different types of values.

8|              [1,"abc"]
               ^^^^^
The 1st element has this type:

    number

But the 2nd is:

    String

Hint: All elements should be the same type of value so that we can iterate
through the list without running into unexpected values.


> 

요소 가져 오기

> ourList = [1,2,3,4,5]
[1,2,3,4,5] : List number
>
> firstElement = List.head ourList
Just 1 : Maybe Int
>
> allButFirst = List.tail ourList
Just [2,3,4,5] : Maybe (List Int)

Maybe 다음과 같은 시나리오 때문에 Maybe 형식으로이 래핑됩니다.

List.head 는 빈 목록을 반환해야합니까? Elm에는 예외 또는 null이 없음을 기억하십시오.

> headOfEmpty = List.head []
Nothing : Maybe Int
>
> tailOfEmpty = List.tail []
Nothing : Maybe (List Int)
>
> tailOfAlmostEmpty = List.tail [1] -- warning ... List is a *linked list* :)
Just [] : Maybe (List Int)

목록의 모든 요소 변환하기

List.map : (a -> b) -> List a -> List b 는 한 매개 변수 함수를 목록의 각 요소에 적용하여 수정 된 값으로 새 목록을 반환하는 고차 함수입니다.

import String

ourList : List String
ourList = 
    ["wubba", "lubba", "dub", "dub"]

lengths : List Int
lengths = 
    List.map String.length ourList
-- [5,5,3,3]

slices : List String
slices =
    List.map (String.slice 1 3) ourList
-- ["ub", "ub", "ub", "ub"]

요소의 색인을 알아야 할 경우 List.indexedMap : (Int -> a -> b) -> List a -> List b 을 사용할 수 있습니다 List.indexedMap : (Int -> a -> b) -> List a -> List b :

newList : List String
newList =
    List.indexedMap (\index element -> String.concat [toString index, ": ", element]) ourList
-- ["0: wubba","1: lubba","2: dub","3: dub"] 

목록 필터링

List.filter : (a -> Bool) -> List a -> List a 는 임의의 값에서 부울로 단일 매개 변수 함수를 취하여 해당 함수를 주어진 목록의 모든 요소에 적용하는 고차 함수입니다. 함수가 True 를 반환하는 요소 만 유지합니다. List.filter 가 첫 번째 매개 변수로 사용하는 함수는 종종 술어 (predicate) 라고합니다.

import String

catStory : List String
catStory = 
    ["a", "crazy", "cat", "walked", "into", "a", "bar"]

-- Any word with more than 3 characters is so long!
isLongWord : String -> Bool
isLongWord string =
    String.length string > 3

longWordsFromCatStory : List String
longWordsFromCatStory = 
    List.filter isLongWord catStory

elm-repl 에서 이것을 평가하십시오.

> longWordsFromCatStory
["crazy", "walked", "into"] : List String
>
> List.filter (String.startsWith "w") longWordsFromCatStory
["walked"] : List String

목록의 패턴 매칭

목록을 구성하는 생성자가 중위 함수 :: 에서 다른 방식으로 다른 목록과 일치 할 수 있습니다. (어떻게 작동하는지에 대한 목록 작성 예제를 참조하십시오.)

matchMyList : List SomeType -> SomeOtherType
matchMyList myList = 
    case myList of
        [] -> 
            emptyCase

        (theHead :: theRest) ->
            doSomethingWith theHead theRest

원하는만큼 많은 요소를 목록에서 일치시킬 수 있습니다.

hasAtLeast2Elems : List a -> Bool
hasAtLeast2Elems myList =
    case myList of
        (e1 :: e2 :: rest) -> 
            True
    
        _ -> 
            False

hasAtLeast3Elems : List a -> Bool
hasAtLeast3Elems myList =
    case myList of
        (e1 :: e2 :: e3 :: rest) -> 
            True
    
        _ -> 
            False

목록에서 n 번째 요소 가져 오기

List 는 "임의 액세스"를 지원하지 않습니다. 즉, 첫 번째 요소보다 목록에서 다섯 번째 요소를 가져 오는 데 더 많은 작업이 필요하므로 결과적으로 List.get nth list 기능이 없습니다. 하나는 처음부터 끝까지 가야합니다 ( 1 -> 2 -> 3 -> 4 -> 5 ).

무작위 액세스가 필요한 경우 Array 와 같은 임의 액세스 데이터 구조를 사용하면 더 나은 결과 (및 성능)를 얻게 될 것입니다. 첫 번째 요소를 가져가는 것은 말하자면 1000 번째 작업과 동일한 작업량을 사용합니다. (복잡도 O (1)).

그럼에도 불구하고 n 번째 요소를 얻는 것은 가능합니다.

get : Int -> List a -> Maybe a
get nth list =
    list
        |> List.drop (nth - 1)
        |> List.head

fifth : Maybe Int
fifth = get 5 [1..10]
--    = Just 5

nonexistent : Maybe Int
nonexistent = get 5 [1..3]
--          = Nothing

다시 말하지만, 이것은 nth 논의가 커질수록 더 많은 작업을 필요로합니다.

목록을 단일 값으로 줄이기

느릅 나무에서 함수를 줄이는 것을 "접기"라고하며, 왼쪽에서 foldl 오른쪽에서 foldr 값을 "접는"두 가지 표준 방법이 있습니다.

> List.foldl (+) 0 [1,2,3]
6 : number

foldlfoldr 대한 인수는 foldl 과 같습니다.

  • 감소 함수 : newValue -> accumulator -> accumulator
  • 축 압기 시작 값
  • 줄이려는 목록

사용자 정의 함수를 사용한 또 다른 예제 :

type alias Counts =
    { odd : Int
    , even : Int
    }

addCount : Int -> Counts -> Counts
addCount num counts =
    let
        (incOdd, incEven) =
            if num `rem` 2 == 0
                then (0,1)
                else (1,0)
    in
        { counts
            | odd = counts.odd + incOdd
            , even = counts.even + incEven
        }

> List.foldl
      addCount
      { odd = 0, even = 0 }
      [1,2,3,4,5]
{ odd = 3, even = 2 } : Counts

위의 첫 번째 예에서 프로그램은 다음과 같이 진행됩니다.

List.foldl (+) 0 [1,2,3]
3 + (2 + (1 + 0))
3 + (2 + 1)
3 + 3
6
List.foldr (+) 0 [1,2,3]
1 + (2 + (3 + 0))
1 + (2 + 3)
1 + 5
6

(+) 와 같은 교환 가능한 함수의 경우 실제로 차이가 없습니다.

그러나 (::) 어떤 일이 일어나는지보십시오.

List.foldl (::) [] [1,2,3]
3 :: (2 :: (1 :: []))
3 :: (2 :: [1])
3 :: [2,1]
[3,2,1]
List.foldr (::) [] [1,2,3]
1 :: (2 :: (3 :: []))
1 :: (2 :: [3])
1 :: [2,3]
[1,2,3]

값을 반복하여 목록 만들기

> List.repeat 3 "abc"
["abc","abc","abc"] : List String

List.repeat 임의의 값을 부여 할 수 있습니다.

> List.repeat 2 {a = 1, b = (2,True)}
[{a = 1, b = (2,True)}, {a = 1, b = (2,True)}]
  : List {a : Int, b : (Int, Bool)}

목록 정렬

기본적으로 List.sort 는 오름차순으로 정렬합니다.

> List.sort [3,1,5]
[1,3,5] : List number

List.sort 는 목록 요소를 comparable 수 있어야 comparable . 그 의미 : String , Char , number ( IntFloat ), Listcomparable 또는 튜플comparable .

> List.sort [(5,"ddd"),(4,"zzz"),(5,"aaa")]
[(4,"zzz"),(5,"aaa"),(5,"ddd")] : List ( number, String )

> List.sort [[3,4],[2,3],[4,5],[1,2]]
[[1,2],[2,3],[3,4],[4,5]] : List (List number)

List.sort 하여 Bool 또는 객체 목록을 정렬 할 수 없습니다. 자세한 내용은 사용자 지정 비교기를 사용하여 목록 정렬을 참조하십시오.

> List.sort [True, False]
-- error, can't compare Bools

사용자 지정 비교기로 목록 정렬

List.sortWith 사용하면 임의의 모양의 데이터로 목록을 정렬 할 수 있습니다. 비교 함수를 사용하여 목록을 정렬 할 수 있습니다.

compareBools : Bool -> Bool -> Order
compareBools a b =
    case (a,b) of
        (False, True) ->
            LT

        (True, False) ->
            GT

        _ ->
            EQ
        
> List.sortWith compareBools [False, True, False, True]
[False, False, True, True] : List Bool

목록 반전

참고 : List 의 특성으로 인해 이것은 효율적이지 않습니다 (아래 비고 참조). 목록구성하는 것보다 처음부터 "올바른"방법으로 목록 을 구성한 다음 역순으로 구성하는 것이 좋습니다.

> List.reverse [1,3,5,7,9]
[9,7,5,3,1] : List number

목록을 내림차순으로 정렬

기본적으로 List.sortcompare 함수를 사용하여 오름차순으로 정렬합니다.

내림차순으로 정렬하는 두 가지 방법이 있습니다 : 하나는 효율적이고 다른 하나는 비효율적입니다.

  1. 효율적인 방법 : List.sortWith 와 내림차순 비교 함수.
descending a b =
    case compare a b of
      LT -> GT
      EQ -> EQ
      GT -> LT

> List.sortWith descending [1,5,9,7,3]
[9,7,5,3,1] : List number
  1. 비효율적 인 방법 (낙담!) : List.sort 그리고 List.reverse .
> List.reverse (List.sort [1,5,9,7,3])
[9,7,5,3,1] : List number

파생 값으로 목록 정렬

List.sortBy 는 요소에 함수를 사용하고 그 결과를 비교에 사용할 수있게합니다.

> List.sortBy String.length ["longest","short","medium"]
["short","medium","longest"] : List String
-- because the lengths are: [7,5,6]

또한 레코드 접근 자와도 잘 작동합니다.

people =
    [ { name = "John", age = 43 }
    , { name = "Alice", age = 30 }
    , { name = "Rupert", age = 12 }
    ]

> List.sortBy .age people
[ { name = "Rupert", age = 12 }
, { name = "Alice", age = 30 }
, { name = "John", age = 43 }
] : List {name: String, age: number}

> List.sortBy .name people
[ { name = "Alice", age = 30 }
, { name = "John", age = 43 }
, { name = "Rupert", age = 12 }
] : List {name: String, age: number}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow