[英]Haskell - Searching the entire list for an char
I have following list:我有以下列表:
charKeys=[('1','a')
,('2','b')
,('3','c')
,('4','d')
,('5','e')]
Now i want to search for an character in the list and replicate the other character three times.现在我想在列表中搜索一个字符并将另一个字符复制三遍。 I want a function like that:
我想要这样的 function :
search x = if x == fst(charKeys !! 0) then replicate 3 (snd(charKeys !! 0)) else "Error"
But this function only check the first index of the list and works only for x == '1'.但是这个 function 只检查列表的第一个索引并且只适用于 x == '1'。
Can somebody help me, that the function also works if x == '2' or '5'?有人可以帮助我,如果 x == '2' 或 '5',function 也可以工作吗?
There are a few ways to do this, and for all of them we will be writing a function that also takes as an input charKeys
.有几种方法可以做到这一点,对于所有这些方法,我们将编写一个 function 作为输入
charKeys
。
The most important would be using recursion:最重要的是使用递归:
search n charKeys = if n == fst (head charKeys) then replicate 3 (snd (head charKeys)) else search n (tail charKeys)
We can rewrite this using pattern matching and function guards like so:我们可以使用模式匹配和 function 守卫来重写它,如下所示:
search n ((k,c):lst) | k == n = replicate 3 c
| otherwise = search n lst
It's also good practice to cover all possible inputs for a pattern match, so we add this additional line:覆盖模式匹配的所有可能输入也是一种很好的做法,因此我们添加了以下附加行:
search _ [] = error "Requested key not found"
These are pretty important concepts in Haskell, so make sure you understand what's going on here before going on.这些是 Haskell 中非常重要的概念,因此请确保在继续之前了解这里发生了什么。
Another solution would be to use the function find
from Data.List
, documented here :另一种解决方案是使用从 Data.List
find
的Data.List
,记录在这里:
import Data.List (find)
search n charKeys = case find ((==n) . fst) charKeys of
Just (_,c) -> replicate 3 c
Nothing -> error "Requested key not found"
Note that we're using a case statement to check whether we've found a matching element in the list, since find
returns a Maybe
.请注意,我们使用 case 语句来检查是否在列表中找到了匹配的元素,因为
find
返回一个Maybe
。 Also, (==n). fst
另外,
(==n). fst
(==n). fst
is a more idiomatic way of saying \x -> fst x == n
, using composition and operator punning. (==n). fst
是一种更惯用的说法\x -> fst x == n
,使用组合和运算符双关语。
We can simplify this even further by using Prelude's lookup
function:我们可以通过使用 Prelude 的
lookup
function 进一步简化这一点:
search n charKeys = case lookup n charKeys of
Just c -> replicate 3 c
Nothing -> error "Requested key not found"
And even more by using maybe
from Data.Maybe
(also using $
):通过使用
maybe
来自Data.Maybe
的更多信息(也使用$
):
search n charKeys = maybe (error "Requested key not found") (replicate 3) $ lookup n charKeys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.