简体   繁体   English

Haskell递归函数和语法

[英]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. 我对haskell很新,并且负责创建一个带有int和int列表的函数,该函数将找到输入的int位置并返回它之前的值,ex fn 5 [1,2,3,4 ,5,6]将返回4.我开始时遇到很多问题。 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 Adams代码错误

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) . 注意我的最后一种情况 - 当你无法匹配模式(x1:x2:xs)时,这是失败的情况。

Alternatively: (x1:x2:xs) could also be spelled (x1:xs@(x2:_)) . 或者: (x1:x2:xs)也可以拼写(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. 而不是重新加入x2xs来递归。

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 . 请注意,此函数可以采用更多态的形式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!" 这允许你将fn与其他有用的类型一起使用,即fn '#' "I'm #1!" gives '1' '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. 此处更好的返回值可能是Maybe Int (或多态形式的Maybe a ),因为您将有一些不包含搜索词的列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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