Nested list comprehensions in Haskell -
i following haskell tutorial , on higher order functions section. defines function called chain as:
chain :: (integral a) => -> [a] chain 1 = [1] chain n | n = n:chain (n `div` 2) | odd n = n:chain (n * 3 + 1)
there exercise find number of "chains" have length longer 15. this:
numlongchains :: int numlongchains = length (filter islong (map chain [1..100])) islong xs = length xs > 15
i trying come list comprehension instead of giving me number of chains gives me list of chains longer 15 [1..100]. closest attempt far looks like:
[ [ | <- chain b, length > 15] | b <- [1..100]]
but get:
<interactive>:9:14: no instance (integral [a0]) arising use of `chain' possible fix: add instance declaration (integral [a0]) in expression: chain b in stmt of list comprehension: <- chain b in expression: [a | <- chain b, length > 15] <interactive>:9:45: no instance (enum [a0]) arising arithmetic sequence `1 .. 100' possible fix: add instance declaration (enum [a0]) in expression: [1 .. 100] in stmt of list comprehension: b <- [1 .. 100] in expression: [[a | <- chain b, length > 15] | b <- [1 .. 100]] <interactive>:9:46: no instance (num [a0]) arising literal `1' possible fix: add instance declaration (num [a0]) in expression: 1 in expression: [1 .. 100] in stmt of list comprehension: b <- [1 .. 100]
am close? want solve problem using nested comprehension sake of learning despite possible better ways approach this.
you're close. you're looking for:
[ | b <- [1..10], let = chain b, length > 15 ]
the expression
[ [ | <- chain b, length > 15] | b <- [1..100]]
has type:
integral [a] => [[[a]]]
which not want, because of haskell's polymorphic numeric literals, could possibly type check if correct definition in place.
in case b
inferred list of type, , why see error:
no instance (integral [a0]) ...
here complete run down on how types inferred.
- from
b <- [1..100]
can inferenum b
constraint - from call
chain b
can inferintegral b
constraint - from
a <- chain b
can infera
,b
have same type - from
length a
can infera
list of something, e.g.a ~ [t]
so (3) , (4) can infer b ~ [t]
, need both integral [t]
, enum [t]
type t
.
to further elaborate on (3), know chain b
list, e.g. [t]
t
type of b
. a <- chain b
know a
has same type elements of chain b
, i.e. type of a
t
.
Comments
Post a Comment