简体   繁体   中英

Usage generics from function type declaration in function body

{-# 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

What do I replace and with in order to make it work? I tried s and i but I get an error Could not match actual type s1 with expected type s on Just x . What can I use to reference types s and I from the function body?

Simple fixes:

  • Add a type signature to equals - otherwise monomorphism bites you
  • Remove the unnecessary type annotation on def & section .~ Just x - the type is inferred anyways.

So:

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM