English 中文(简体)
说明从清单中排出一名特定构造者的首次出现
原标题:Idiomatic way to fetch the first occurrence of a specific constructor from a list
  • 时间:2011-11-19 15:49:25
  •  标签:
  • haskell

是否找到了在清单中首次出现建筑商的明智办法,而没有在下文样本中进行明确的重新检查?

data Elem = A Int | B Char deriving Show

getA :: [Elem] -> Maybe Elem
getA [] = Nothing
getA (e:es) = 
    case e of 
        A a -> Just (A a)
        _   -> getA es
最佳回答

简单

import Data.Maybe (listToMaybe)
getA xs = listToMaybe [e | e@(A _) <- xs]

增编:使用空记录模式(库多斯哈马尔)更妥善、更不受未来影响:

getA xs = listToMaybe [e | e@(A{}) <- xs]

然而,值得注意的是,这只是为了配对建筑商而做的。 对于一般特性,find为:

get prop xs = listToMaybe [e | e <- xs, prop e]
get prop xs = listToMaybe (filter prop xs)
get prop xs = find prop xs
问题回答

http://haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v%3afind>Data.List.find

getA = find isA
   where isA (A {}) = True
         isA _ = False

You could use find:

data Elem = A Int | B Char deriving Show
getA elements = find (x->case x of (A _) -> True; _ -> False) elements




相关问题
Euler Problem in Haskell -- Can Someone Spot My Error

I m trying my hand at Euler Problem 4 in Haskell. It asks for that largest palindrome formed by multiplying two three-digit numbers. The problem was simple enough, and I thought my Haskell-fu was up ...

How does foldr work?

Can anybody explain how does foldr work? Take these examples: Prelude> foldr (-) 54 [10, 11] 53 Prelude> foldr (x y -> (x+y)/2) 54 [12, 4, 10, 6] 12.0 I am confused about these executions....

Efficient queue in Haskell

How can I efficiently implement a list data structure where I can have 2 views to the head and end of the list, that always point to a head a tail of a list without expensive calls to reverse. i.e: ...

Problem detecting cyclic numbers in Haskell

I am doing problem 61 at project Euler and came up with the following code (to test the case they give): p3 n = n*(n+1) `div` 2 p4 n = n*n p5 n = n*(3*n -1) `div` 2 p6 n = n*(2*n -1) p7 n = n*(5*n -3)...

Ways to get the middle of a list in Haskell?

I ve just started learning about Functional Programming, using Haskel. I m slowly getting through Erik Meijer s lectures on Channel 9 (I ve watched the first 4 so far) and in the 4th video Erik ...

haskell grouping problem

group :: Ord a => [(a, [b])] -> [(a, [b])] I want to look up all pairs that have the same fst, and merge them, by appending all the list of bs together where they have the same a and discarding ...

Closest equivalent to subprocess.communicate in Haskell

I want to do a popen() / python s subprocess.communicate from Haskell - start a program, give it stdin, and get its stdout/stderr. What s the most direct / Haskellish way to do this?

热门标签