I try to write custom function which take an array and iterate it, i need to print every digit and recursive launch the same function but i get error
parse error on input `main’
code:
firstitem n = if n /= [] n firstitem( tail n )
main = do
print(firstitem [1,2,3])
Your first problem is that you have the wrong syntax for an
ifstatement. You should writeSecond, it’s not clear what the function
firstItemis supposed to do. It sounds like it’s supposed to return the first item of a list, but your description makes it seem as though you want to iterate over all elements of the list.You can combine the iteration and printing into a single function like this:
The function
nullreturnsTrueif the list is empty, otherwise it returnsFalse. The statementreturn ()you can think of as saying “there’s nothing more to process, so stop the function now and return no result”. The third and fourth lines contain a “do block”. The do block is basically a bit of glue that binds the two actionsprint (head xs)andprintAll (tail xs)together into one action. You can write it with curly braces to make it a bit clearer:although you don’t actually need them – the indentation specifies what you mean.
This solves your problem, but it’s a bit clunky. Haskell is supposed to be a beautiful language, after all – so let’s make your code beautiful! It would be better to use pattern matching to pull the list apart into its head and tail:
That’s a lot better. But it could be more modular. Hey, maybe we could make a generic function that takes an action as input, and does that action for every element of the list:
That’s neat. But actually, there’s already a function that does this. It’s called
mapM_(there is a good reason for it being called this, but I won’t get into it now) and it’s in theControl.Monadmodule:Actually, you can leave off the
xsargument, and the compiler can infer that it’s supposed to be there:Finally, your code is beautiful. Hope that helps a bit.