user3928256
user3928256

Reputation: 993

What does this function do in Haskell? I'm confused with the type

q3 a (b:[]) = a b
q3 a (b1:b2:bs) = q3 a (b2:bs)

It seems like a doesn't have any influence to the function. My understanding is that this function takes two parameters, where the second one is a list, and returns the first parameter and the tail of the second list. However, I'm confused by the type:

q3 :: (t1 -> t) -> [t1] -> t

How is a relevant to t1 -> t? Thank you.

Upvotes: 1

Views: 163

Answers (2)

viorior
viorior

Reputation: 1803

You could rewrite this function.

q3 :: (t1 -> t) -> [t1] -> t
q3 a (b:[]) = a b
q3 a (b1:b2:bs) = q3 a (b2:bs)

to 'usual' style

q3 :: (a -> b) -> [a] -> b
q3 f (a:[]) = f a
q3 f (a1:a2:as) = q3 f (a2:as)

Now it is easy to see, that q3 f as = f (last as). Function q3 apply function f to the last element of the list as

Upvotes: 1

Mihai Maruseac
Mihai Maruseac

Reputation: 21425

The first line of the function has a b after the equal sign. Thus a has to be a function since that is a function application. Since b is the type of the elements of the list then a is a function from the type of elements in the list to the return type of the function.

The function just applies a to the last element of the list. Thus, it is similar to a . last.

Upvotes: 8

Related Questions