147pm
147pm

Reputation: 2237

Defining secondary function in where

I have this which works

import Data.List
import Data.Maybe

mI l n | l == [] = Nothing
       | n == 0 = Just h
       | otherwise = mI t (n-1)
  where h = head l
        t = tail l

and then this, which successfully allows me to get a number value out of Just

myIndex l n
  | m == Nothing = error "No list."
  | otherwise = fromJust m 
      where m = mI l n

And yet I can't do this without an error

myIndex' l n
  | m == Nothing = error "No list."
  | otherwise = fromJust m
      where m = mI l n | l == [] = Nothing
                       | n == 0 = Just h
                       | otherwise = mI t (n-1)
                   where h = head l
                         t = tail l

...

error: parse error on input `|'

Why won't it allow me to define the secondary function within the second where?

Upvotes: 0

Views: 51

Answers (2)

DDub
DDub

Reputation: 3924

Your line

  where m = mI l n ...

doesn't make sense. Are you defining m or are you defining a function mI? I think what you want is:

  where m = mI l n
        mI l n | l == ...

Also, it would be better to use patterns, e.g.

mI [] n = Nothing
mI (h:t) n | n == 0 = Just h
           | otherwise = mI t (n-1)

Upvotes: 3

Fyodor Soikin
Fyodor Soikin

Reputation: 80714

You're trying to cram the definitions of both m and mI into one definition.

What you probably meant to do what this:

myIndex' l n
  | m == Nothing = error "No list."
  | otherwise = fromJust m
      where m = mI l n
            mI l n | l == [] = Nothing
                   | n == 0 = Just h
                   | otherwise = mI t (n-1)
                   where h = head l
                         t = tail l

Upvotes: 3

Related Questions