Haskell通过空字符到一个函数 [英] Haskell passing empty Character to a function
问题描述
我在Haskell工作有两个函数:
I'm working in Haskell in two functions:
基本上,我想在匹配给定字符串中的特定字符之前获取字符
Basically I want to get the character before matching a specific character in a given string
这是我的代码:
before :: Char -> [Char] -> Char
before x str = trackelement x ' ' str
trackelement :: Char -> Char -> [Char] -> Char
trackelement x y (z:zs)
| x == z = y
| otherwise = trackelement x z (zs)
我的问题是当我尝试: before 'l'luis
My problem is when I try: before 'l' "luis"
答案是:''
,'l'
没有任何东西),我想要''
或 Nothing
The answer is : ' '
(of course, before 'l'
there is nothing), and I would like to be ''
or Nothing
我尝试通过 trackelement x''str
,而不是 trackelement x''str
但我有这个错误语法错误在''str
I tried passing trackelement x '' str
instead of trackelement x ' ' str
but I have this error Syntax error on ''str
您可以使用
Could you suggest me something?
推荐答案
$ c>:
before :: Char -> [Char] -> Maybe Char
before x str = initialise x str
initialise x (y:xs)
| x == y = Nothing
| otherwise = trackelement x y xs
trackelement :: Char -> Char -> [Char] -> Maybe Char
trackelement x y [] = Nothing
trackelement x y (z:zs)
| x == z = Just y
| otherwise = trackelement x z zs
为了处理 'luis
,我们必须添加一个新的初始化函数。它基本上检查第一个字符是否匹配搜索的字符。如果是,我们返回 Nothing
,因为我们检查第一个字符,显然没有前一个。否则我们只需调用 trackelement
并使用它的结果。
To take care of the corner case before 'l' "luis"
, we have to add a new initialiser function. It basically checks if the first character matches the searched one. If it does, we return Nothing
, because we checked the first character which obviously does not have a preceding one. Else we just call trackelement
and use it's result.
Zeta提到,你可以结合功能,这简化了一切,并照顾你目前遇到的角落情况。
As Zeta mentioned, you can combine the functions, which simplifies everything and takes care of the corner case you are currently experiencing.
before _ [x] = Nothing
before a (x:y:xs)
| a == y = Just x
| otherwise = before a (y:xs)
只要使用这个函数,一个包含多个字母的单词,也搜索( before'a'amalia
- > Just'm'
)。目前,我知道的最好的解决方案是再次分裂成多个功能,这使我们回到顶部的解决方案。
Just using this function, you noticed you have problems when encountering a word containing more than one letter which is also searched for (before 'a' "amalia"
-> Just 'm'
). Currently the best solution I know of is again splitting this up into more than one function, which brings us back to the solution at the top.
这篇关于Haskell通过空字符到一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!