简体   繁体   中英

Haskell recursion functions and syntax

I am quite new to haskell and was tasked with creating a function that takes an int and a list of ints, the function would find the inputted ints position and return the value prior to it, ex fn 5 [1,2,3,4,5,6] would return 4. I'm having many problems getting started. First off I keep getting Variable is not in scope errors.

fn' ::Int->[Int]->Int
fn' y [] = -1
fn' y (x:xs)
    |y = (head listail) = x 
    |otherwise = listail
    where listail = fn' y (tail)xs

Where should I start looking at, and in general are there other things I should or shouldn't do?

Adams code error

main.hs:3:31: error:

• Couldn't match expected type ‘Int’ with actual type ‘[Int]’
• In the expression: fn y x2 : xs
  In an equation for ‘fn’:
      fn y (x1 : x2 : xs)
        | y == x2 = x1
        | otherwise = fn y x2 : xs
main.hs:3:36: error:
• Couldn't match expected type ‘[Int]’ with actual type ‘Int’
• In the second argument of ‘fn’, namely ‘x2’
  In the first argument of ‘(:)’, namely ‘fn y x2’
  In the expression: fn y x2 : xs
<interactive>:3:1: error:
• Variable not in scope: main
• Perhaps you meant ‘min’ (imported from Prelude)

You can use pattern matching to grab out two values from the list and compare them.

fn :: Int -> [Int] -> Int
fn y (x1:x2:xs) | y == x2 = x1
                | otherwise = fn y (x2:xs)
fn _ _ = -1

Note my last case -- this is the fail case, when you can't match the pattern (x1:x2:xs) .

Alternatively: (x1:x2:xs) could also be spelled (x1:xs@(x2:_)) . The latter pattern is more complicated to read, but lets you do:

fn :: Int -> [Int] -> Int
fn y (x1:xs@(x2:_)) | y == x2 = x1
                    | otherwise = fn y xs
fn _ _ = -1

rather than re-joining x2 and xs to recurse.

Try it online!


As gallais points out in the comments:

Note that this function can take the more polymorphic form Eq a => a -> [a] -> a . This is just a change to the type signature

fn :: Eq a => a -> [a] -> a

This lets you use fn with other useful types, ie fn '#' "I'm #1!" gives '1'

Also a better return value here might be a Maybe Int (or a Maybe a in the polymorphic form), since you'll have some lists that don't contain the search term.

fn :: Eq a => a -> [a] -> Maybe a
fn y (x1:xs@(x2:_)) | y == x2 = Just x1
                    | otherwise = fn y xs
fn _ _ = Nothing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM