函数体中函数类型声明的用法泛型

时间:2016-06-29 02:48:51

标签: haskell

{-# LANGUAGE TemplateHaskell, DeriveGeneric, DeriveAnyClass #-}
module Main where
import Flow
import Control.Lens hiding ((|>))
import Data.Default
import GHC.Generics

main :: IO ()
main = putStrLn "hello world"

append x = (++ [x])
equals = (==)

data SectionedItems s i = SectionedItems{
    _section :: Maybe s,
    _items :: [i],
    _subsections :: [SectionedItems s i]
} deriving (Show, Generic)

instance Default (SectionedItems s i) where
  def = SectionedItems { _section = Nothing, _items = [], _subsections = [] }

makeLenses ''SectionedItems

sectionedItems = SectionedItems{
    _section = Nothing,
    _items = [],
    _subsections = []
}

data SectionedItemsElement s i = Section s | Item i


addElementToSectionedItems :: SectionedItems s i -> SectionedItemsElement s i -> SectionedItems s i
addElementToSectionedItems si (Section x) =
    (def & section .~ Just x :: SectionedItems s i) -- Error is probably somewhere here
    |> \subsec -> si & subsections %~ append subsec

为了使其有效,我应该更换什么?我尝试了s和i但我在Could not match actual type s1 with expected type s上收到错误Just x。我可以用什么来从函数体中引用类型s和I?

1 个答案:

答案 0 :(得分:2)

简单修复:

  • equals添加类型签名 - 否则单态会咬你
  • 删除def & section .~ Just x上不必要的类型注释 - 无论如何都会推断出类型。

所以:

...

equals :: Eq a => a -> a -> Bool
equals = (==)
...
addElementToSectionedItems :: SectionedItems s i -> SectionedItemsElement s i -> SectionedItems s i
addElementToSectionedItems si (Section x) =
    (def & section .~ Just x)
    |> \subsec -> si & subsections %~ append subsec