What would be a shorter syntax for this function? I'm noticing that a lot of programmers use pipes in their functions, but I'm stuck trying to figure out how I could do the same for this one.
fun test (i, x) =
if null x
then false
else
if hd x = i then true
else test(i, tl x)
//
val test = fn : ''a * ''a list -> bool
Here is a shorter version:
fun test (_, []) = false
| test (i, x::xs) = (x = i) orelse test (i, xs)
Here are the things I did:
Use pattern matching. In your second solution you're already pattern matching against the empty list, so this takes it a step further and pattern matches on the non-empty list (x::xs
), making the use of hd
and tl
unnecessary.
Use the _
pattern when you don't need the value.
Instead of if P then true else Q
, write P orelse Q
.
The parenthesis around x = i
isn't strictly necessary. It looks a little confusing with the two different =
s next to one another (one comes from the function definition, and the other is a binary operator), but this is also perfectly valid and means the same:
fun test (_, []) = false
| test (i, x::xs) = x = i orelse test (i, xs)
Or indented a bit more conveniently:
fun test (_, []) = false
| test (i, x::xs) =
x = i orelse test (i, xs)