Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell beginner order function

Tags:

haskell

My code:

isOrdered :: (a -> a -> Bool) -> [a] -> Bool
isOrdered mark xs =(head xs) `mark`(head(tail xs)) 

Compiles perfectly but when I try to call it with

isOrdered < [1,2,3]

I get an error:

Couldn't match expected type `(a0 -> a0 -> Bool) -> [a0] -> Bool'
            with actual type `[t0]'
In the second argument of `(<)', namely `[1, 2, 3]'
In the expression: isOrdered < [1, 2, 3]
In an equation for `it': it = isOrdered < [1, 2, 3]

What am I missing here?

like image 914
Kalev Kärpuk Avatar asked Feb 07 '26 21:02

Kalev Kärpuk


1 Answers

Since < is infix, you have to wrap it in parens. This converts it to be prefixed.

1 < 2 ==> (<) 1 2
1 + 5 ==> (+) 1 5

Then you're code becomes

isOrdered (<) [1, 2, 3]

This is actually part of a more general concept of sectioning. You can completely convert an infix operator to prefix with parens, or partially apply it like this

\x -> x + 1 ===> (+1)
\x -> 2 ^ x ===> (2^)

The only place where this goes a bit pear-shaped is with -. Since - is a super special prefix operator defined by the Haskell language, you can't do (-2), since it's not clear whether this is a section or a number. Haskell chooses a number, but if you want a section, there is a function subtract.

\x -> x - 2 ==> subtract 2
like image 195
Daniel Gratzer Avatar answered Feb 09 '26 10:02

Daniel Gratzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!