[Haskell-cafe] Can I check the length in a guarded expresion
Andy Morris
andy at adradh.org.uk
Sun Nov 9 18:59:39 UTC 2014
You also forgot the `|` and `=` either side of the `otherwise`. So the weird error is because GHC is understanding the second clause to be the application `a otherwise last3 (tail a)`.
> On 09 Nov 2014, at 19:51, 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 <https://www.haskell.org/mailman/listinfo/beginners>
>>
>> On Sun, Nov 9, 2014 at 10:33 AM, Roelof Wobben <r.wobben at home.nl <mailto: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 <mailto:Haskell-Cafe at haskell.org>
>> http://www.haskell.org/mailman/listinfo/haskell-cafe <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/1a0d5ac1/attachment-0001.html>
More information about the Haskell-Cafe
mailing list