Ok, maybe the title is a little confusing, but what I am trying to do is have a function like this: f (a:b:c:d:is) = ...
but be able to refer to a:b:c:d
without writing it again. As it turns out, I can't do something like e@(a:b:c:d):is
and get the expected result. Any ideas?
Using as-patterns not binding to the full List in Haskell
Asked Answered
You'll want to user the proper syntax, e@(a:b:c:d:is) –
Eyeball
Oh I see what you're getting at. If you're using (e@(a:b:c:d):is), then it's a list of lists with d being the tail of the inner lists. I don't think you can help this with as patterns, since the parens for grouping will be necessary. –
Eyeball
The best I can think of is using view patterns, like this:
{-# LANGUAGE ViewPatterns #-}
f (splitAt 4 -> (as@[a,b,c,d], is)) = is ++ [d,c,b,a] ++ as
You could avoid the language pragma by just using pattern guards. "f xs | (e@[a,b,c,d], is) <- splitAt 4 xs = e" –
Eyeball
I was hoping for something as 'clean' as as-patterns, but thanks anyway. –
Frau
You can't do that, one reason is that a:b:c:d
is not a well-typed expression. By the binding in the definition of f
, a, b, c, d
all have the same type, say t
, but the type of the list constructor is
(:) :: t -> [t] -> [t]
You can sort-of achieve what you want by binding let foo = take 4 inputList
. Admittedly clunky, but I can't think of anything better off the top of my head.
© 2022 - 2024 — McMap. All rights reserved.