how can 开发者_开发知识库I easily take the following
[4]
and return the following:
4
I know that [4]!!0 works but doesn't seem to be a good strategy...
Just pattern match it:
getSingleton [a] = a
head
is the normal answer, which you see three of (one with a custom name) - this is functionally the same as what you already know (x !! 0
~ head x
). I strongly suggest against partial functions unless you can prove (with local knowledge) that you'll never pass an empty list and result in a run-time exception.
If your function doesn't guarantee a non-empty list then use listToMaybe :: [a] -> Maybe a
:
> listToMaybe [4]
Just 4
> listToMaybe [5,39,-2,6,1]
Just 5
> listToMaybe []
Nothing -- A 'Nothing' constructor instead of an exception
Once you have the Maybe a
you can pattern match on that, keep it as Maybe and use fmap
or a Maybe monad, or some other method to perform further operations.
Alternatively to gatoatigrado's solution you can also use the head
function, which extracts the first element of a list, but will also work on lists with more than one element and additionally is a standard function in the Prelude. You just have to be careful not to apply it to empty lists or you will get a runtime exception.
Prelude> head [4]
4
Prelude> head []
*** Exception: Prelude.head: empty list
If you want this first item in a list you can just do
head [4]
[]
is a monad. So you use the monad "extract" operation, <-
double x = 2*x
doubleAll xs = do x <- xs
return (double x)
Of course, the result of the monadic computation is returned in the monad. ;)
精彩评论