0

I want to create a function, let's call it altHead, that takes 2 variables and outputs a variable such that:

a -> [a] -> a

I want to call it like this:

altHead 3 [1,2,3,4]

What it should do is to look at the first variable, and the list. If the list is empty, then return the first var's value; otherwise, return the list.

In this case, I've written the following code.

altHead :: a -> [a] -> a
altHead (x:xs) = if null[xs] then [x] else [xs]

However, I believe x:xs only looks through the list.

I'm a bit stuck as to how to change this so that it looks at the first value as well, and how to include the first value in the function.

6
  • 2
    Hint: don't use if/then/else at all. Pattern matching is all you need. Commented May 13, 2017 at 22:34
  • @Carl Hmmm so, altHead [] = x //// altHead [a] = [a] ? Commented May 13, 2017 at 22:39
  • 1
    (x:xs) doesn't bind two arguments, it binds the head and tail of a single argument that must be a list. Commented May 13, 2017 at 22:40
  • @Wyzard Aye, this is the conclusion I came to as well. Just wasn't sure how to include the first var in there too... Commented May 13, 2017 at 22:44
  • altHead a (x:xs) = Commented May 13, 2017 at 22:45

1 Answer 1

3

You want something like:

altHead :: a -> [a] -> a
altHead a xs = if null xs then a else head xs

Or alternatively, using pattern matching on the list:

altHead :: a -> [a] -> a
altHead a [] = a
altHead a (x:xs) = x
Sign up to request clarification or add additional context in comments.

7 Comments

The last line of the second example can also be written altHead _ (x:_) = x, since neither a nor xs are actually used.
Yes, I just thought it helped readability/understanding to leave them as variable names. (It also shows the (x:xs) pattern that the OP used.)
I think I now understand something I had fundamentally MISunderstood previously. Thanks for this, saw it just as I had finished my version, and it was a little bit off, but otherwise ok. Quick Q: I realise this isn't how typing would work normally, but is it possible for it to return the entire LIST if it's not empty, but otherwise only return x?
You can't have a function that sometimes returns a list and sometimes returns a single value, because those are different types. But you could change the signature to a -> [a] -> [a] and return [a] when the list is empty.
Thank you, this is what I needed. Gonna learn me some more Haskell, cheers guys!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.