简体   繁体   中英

Figuring out type declaration for HOF in Haskell

I am reviewing for an exam and one of the practice problems ask to write the type declaration

mystery :: ---complete here---- 
mystery x p
    | p (head x) = tail x
    | otherwise  = head x : mystery (tail x) p

Without looking at the answer, I thought mystery would be of type:

mystery:: [a] -> a -> [a]

but when I look at the solution to compare:

mystery:: [a] -> (a -> Bool) -> [a]

Why is a -> Bool ? and what in the lines of code can tell me to consider Bool in my type declaration ?

Here's what we know about p :

  1. It is applied to a value, so it must be a function. That makes its type t1 -> t2 for some types t1 and t2 .
  2. It is specifically applied to head x . Since you've already determined that x :: [a] , then head x :: a . This means t1 ~ a , and so p :: a -> t2 .
  3. p (head x) is used in a context where a Boolean value is expected, so p (head x) :: Bool . This means t2 ~ Bool , and so p :: a -> Bool .

QED.

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