[Haskell-cafe] Can I check the length in a guarded expresion

Jeffrey Brown jeffbrown.the at gmail.com
Sun Nov 9 18:55:58 UTC 2014


The first guard returns a Maybe [a]. The second and third return an [a]. To
make them all return the same type, you should be wrapping the second and
third return values in a Just constructor.

On Sun, Nov 9, 2014 at 10:51 AM, Roelof Wobben <r.wobben at home.nl> wrote:

>  Hello,
>
> Here is the complete solution :
>
> last3::[a]-> Maybe a;
> last3 a
>   | null a = Nothing
>   | length a == 1 = a
>   otherwise last3 (tail a)
>
> And I see these error messages :
>
> src/Main.hs at 9:21-10:27
> Couldn't match expected type ‘Bool -> ([a0] -> Maybe a0) -> [a] -> Maybe
> a’ with actual type
> [a]
>  Relevant bindings include a :: [a] (bound at
> /home/app/isolation-runner-work/projects/75679/session.207/src/src/Main.hs:7:7)
> last3 :: [a] -> Maybe a (bound at
> /home/app/isolation-runner-work/projects/75679/session.207/src/src/Main.hs:7:1)
> The function
> a
>  is applied to three arguments, but its type
> [a]
>  has none …
>
>
>
>
> Bob Ippolito schreef op 9-11-2014 19:45:
>
> You can do that. If you're getting an error, it's from a mistake on some
> other line. That said, you shouldn't write it that way. length requires a
> traversal of the entire list, so if the list is 1000 elements long it will
> take 1001 steps to compute that result when two steps would do. `length
> (take 2 a) == 1` would be a constant time way to get the result you want,
> although likely not the most elegant way to solve this exercise.
>
>  Perhaps this is the sort of question better suited for the
> haskell-beginners mailing list:
> https://www.haskell.org/mailman/listinfo/beginners
>
> On Sun, Nov 9, 2014 at 10:33 AM, Roelof Wobben <r.wobben at home.nl> wrote:
>
>> Hello,
>>
>> I try to make a guarded solution to find the last item in a list.
>>
>> I thought I could do something like this
>>
>> | length a == 1 = a
>>
>> But then I see a lot of error messages.
>>
>> Is there another way I can check the length of a list with guards ?
>>
>> Roelof
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20141109/56c90ae5/attachment.html>


More information about the Haskell-Cafe mailing list