Haskell 错误:预期类型为“* -> *”,但“电影”具有类型“*”

问题描述 投票:0回答:1

我创建了一个“电影”代数数据类型(根据任务的要求):

data Movie = Movie { title :: String, director :: String, releaseYear :: Int} 

然后添加一个函子:

instance Functor Movie where
    fmap _ Nothing = Nothing 
    fmap f (Movie title director releaseYear) = Movie (f title) (f director) (f releaseYear)

之后我写了几个函数来测试程序的运行:

appendYear :: String -> String
appendYear title = title ++ " (2023)"

sampleMovie :: Movie
sampleMovie = Movie "Cool Film" "Amazing Director" 2000

modifiedMovie :: Movie
modifiedMovie = fmap appendYear sampleMovie

在我尝试调用函数之后...

main :: IO ()
main = do
    print sampleMovie
    print modifiedMovie

...我有以下内容:

[1 of 1] Compiling Main             ( main.hs, main.o )
main.hs:3:18: error:
    • Expected kind ‘* -> *’, but ‘Movie’ has kind ‘*’
    • In the first argument of ‘Functor’, namely ‘Movie’
      In the instance declaration for ‘Functor Movie’
  |
3 | instance Functor Movie where
  |                  ^^^^^

请帮我解决问题。我最近才开始学习Haskell,所以我使用在线编译器

尝试在其他任务上做类似的事情:

data Possibly a = NotThere
                | There a 
                deriving (Show, Functor)
instance Functor Possibly where
    fmap _ NotThere = NotThere
    fmap f (There a) = There (f a)

...但这并没有让我得到任何结果。

haskell functor algebraic-data-types
1个回答
0
投票

这里有几个问题:首先:

fmap _ Nothing = Nothing

没有意义:

Nothing
Maybe
类型的数据构造函数,而不是
Movie
类型。

但最重要的是

Functor
适用于参数化类型:这允许更改类型。因此,这意味着
Movie
应该定义为:

data Movie a = Movie { title :: a, director :: String, releaseYear :: Int}

instance Functor Movie where
    fmap f m(Movie {title=t}) = m { … }

我将实施

部分作为练习。

© www.soinside.com 2019 - 2024. All rights reserved.