2016-07-06 3 views
3

id : Intを持つレコードのMaybe Listをフィールドとして受け取り、そのリストにidが存在するかどうかを調べる汎用関数を作成しようとしています。戻り値は、Found record,NotFoundLoadingというメッセージ(リストがNothingの場合)の3つの状態のいずれかになります。あまりにも一般的なエラーを引き起こすフィルタを持つ注釈関数

これまでエラーが発生しましたが、エラーヘルプ(the linkからの読み込みを含む)からこの問題を解決する方法がわかりません。どうすればこの問題を解決できますか。

import Html exposing (text) 

type alias RecordWithID a = 
    { a | id : Int } 


type alias MyRecord = 
    { id : Int 
    , name : String 
} 

type Find a 
    = Found (RecordWithID a) 
    | NotFound 
    | Loading 


findById : Int -> Maybe (List (RecordWithID a)) -> Find (RecordWithID a) 
findById id maybeItems = 
    case maybeItems of 
    Just items -> 
     let 
     head = List.head <| List.filter (\x -> x.id == id) items 
     in 
     case head of 
      Just item -> 
      Found item 

      Nothing -> 
      NotFound 

    Nothing -> 
     Loading 


main = text <| toString <| findById 4 (Just [ MyRecord 4 "hi" ]) 

編集

エラー:

-- TYPE MISMATCH --------------------------------------------------------------- 

The type annotation for `findById` does not match its definition. 

17| findById : Int -> Maybe (List (RecordWithID a)) -> Find (RecordWithID a) 
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
The type annotation is saying: 

    Int -> Maybe (List { b | id : Int }) -> Find { b | id : Int } 

But I am inferring that the definition has this type: 

    Int -> Maybe (List { b | id : Int }) -> Find b 

Hint: A type annotation is too generic. You can probably just switch to the type 
I inferred. These issues can be subtle though, so read more about it. 
<https://github.com/elm-lang/elm-compiler/blob/0.17.0/hints/type-annotations.md> 

私はフィルタと頭からレコードの種類は必ずしもaに一致するが、問題を解決する方法について不明な点がないことを理解。あなたはもともとそれをコード化されたとして、あなたはFind aの定義を守れば、

type Find a 
    = Found a 
    | NotFound 
    | Loading 

をするか、このようなあなたの機能に注釈を付けることができ、::あなたはより一般的Find aを再定義する場合

答えて

4

これは正常にコンパイルされます

findById : Int -> Maybe (List (RecordWithID a)) -> Find a 

なぜこのように動作しますか?私は推測しかできない。 の場合は、Haskellのtypeclassの制約のような感じです(例:findById :: Record a => Int -> Maybe (List a) -> Find a、Elmバージョンのaはアノテーションに1度しか制約できません)。コンパイラには当てはまりませんがまた、それはちょうど投機です。

+1

偉大な、感謝の答え! –

関連する問題