简体   繁体   English

为什么有时 function 在其定义中具有参数但在实际 function 中没有参数?

[英]why sometimes a function that has parameters inside its definition but in the actual function does not have any?

This is the piece of code that I am trying to understand这是我试图理解的一段代码

data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun

isWeekend :: Day -> Bool
isWeekend Sat = True
isWeekend Sun = True
isWeekend _ = False

isWeekday :: Day -> Bool
isWeekday = not.isWeekend

If I am trying to evaluate isWeekday Mon (I specified an argument of type Day from the function definition even if the actual function does not have it), it works.如果我试图评估 isWeekday Mon (我从 function 定义中指定了 Day 类型的参数,即使实际的 function 没有它),它也有效。 If I am modifying the isWeekday into isWeekday day, I have the following error: Couldn't match expected type Bool' with actual type Day -> Bool'.如果我将 isWeekday 修改为 isWeekday 日,则会出现以下错误:无法将预期类型Bool' with actual type Day -> Bool' 匹配。 Could somebody please tell me why I have to skip the parameter which has the type Day?有人可以告诉我为什么我必须跳过类型为 Day 的参数吗? Thank you!谢谢!

the reason that not. isWeekend not. isWeekend not. isWeekend has type Day -> Bool is because not. isWeekend not. isWeekend有类型Day -> Bool是因为not. isWeekend not. isWeekend will return a function. not. isWeekend返回function。 A key aspect of functional programming is that functions are "first class citizens": you can pass functions as parameters, and return functions.函数式编程的一个关键方面是函数是“第一个 class 公民”:您可以将函数作为参数传递,并返回函数。

Since (.) has type (.):: (b -> c) -> (a -> b) -> (a -> c) , and not has type not:: Bool -> Bool , this means that not. isWeekend由于(.)的类型为(.):: (b -> c) -> (a -> b) -> (a -> c) ,而not的类型为not:: Bool -> Bool ,这意味着not. isWeekend not. isWeekend , or more canonical (.) not isWeekend thus has type: not. isWeekend或更规范的(.) not isWeekend因此具有类型:

(.) :: ( b   ->  c  ) -> ( a  ->  c  ) -> ( b  ->  c  )
not ::  Bool -> Bool
isWeekend ::              Day -> Bool
--------------------------------------------------------
not . isWeekend ::                         Day -> Bool

This expression this will return a function that takes a Day as parameter and returns a Bool .这个表达式 this 将返回一个 function ,它接受一个Day作为参数并返回一个Bool

You can write a version of isWeekday with a parameter:你可以编写一个带有参数的isWeekday版本:

isWeekday :: Day -> Bool
isWeekday day = not (isWeekend day)

But then you thus can not define this as isWeekday2 day = not. isWeekend但是,您因此不能将其定义为isWeekday2 day = not. isWeekend isWeekday2 day = not. isWeekend , since then it means that day is a "useless" parameter, and it will still return a function, so then the signature is isWeekday2:: a -> Day -> Bool . isWeekday2 day = not. isWeekend ,从那时起它意味着那day是一个“无用”的参数,它仍然会返回一个 function,所以签名是isWeekday2:: a -> Day -> Bool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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