首页 > 解决方案 > 对haskell'也许'感到困惑,有人可以帮助我吗?

问题描述

我的自制数据类型位置定义如下:

data Location = Location String Int

我所需的功能如下所示:

Function:: String-> Maybe Location
Funtion s
    |head(s)`elem`['A','B','C','D','E','F','G','H'] && last(s) `elem`['1','2','3','4'] = Just Location head(s) digitToInt(last(s))
    |otherwise = Nothing

但是,当我尝试在终端中运行时,它会显示:

Couldn't match expected type ‘([a0] -> a0)
                              -> String -> (Char -> Int) -> Char -> Maybe Location’
            with actual type ‘Maybe (String -> Int -> Location)’
The function ‘Just’ is applied to five arguments,
but its type ‘(String -> Int -> Location)
              -> Maybe (String -> Int -> Location)’
has only one

标签: haskellfunctional-programming

解决方案


语法

f x y

表示将函数f应用于参数xy。请注意,调用 不需要括号f。但是,如果xy本身是复杂的表达式,它们可能需要括号来将该表达式的各个部分组合成一个参数。假设我想应用于f论点g vh w. 对比:

f g v h w -- f applied to g, v, h, and w; not what I wanted
f (g v) (h w) -- f applied to (g v) and (h w); what I wanted

由于括号只是组表达式,并且它们本身不是函数调用语法的一部分,这意味着我们还有:

f g (v) h (w) -- f applied to g, (v), h, and (w)
f g(v) h(w) -- still f applied to g, (v), h, and (w)

所以,当你写

Just Location head(s) digitToInt(last(s))

这意味着适用Just于五个参数,即、Location、、和。可能不是你想要的!head(s)digitToInt(last(s))

希望这可以为您提供足够的信息,以便再次尝试用括号括起来以表示您的意图。


推荐阅读