简体   繁体   中英

Haskell: List append operation

I'm looking at 99 problems solved in Haskell . I'm trying to understand few basics here.

    combinations :: Int -> [a] -> [[a]]
    combinations _ [] = [[]]
    combinations 0 _  = [[]]
    combinations k (x:xs) = x_start ++ others
    where x_start = [ x : rest | rest <- combinations (k-1) xs ]
          others  = if k <= length xs then combinations k xs else []

consider, combinations 1 [3, 4]

pattern matches with the combinations k (x:xs) . We will start with computing x_start which will be x_start = [3 : combinations 0 [4]]

combinations 0 [4] will pattern match with combinations 0 [4] and "return" [[]] (a list of 1 elem empty list)

we now see x_start = [3 : combinations 0 [4]] ===> x_start = [3 : [[]]] . Is this correct? if so what would x_start be at this point, going by list prepend operator : , will x_start = [[3, []]] which is not same as [[3]]?

when I try to print this in ghci, it complains

No instance for (Num [t0]) arising from a use of ‘it’
In a stmt of an interactive GHCi command: print it

We will start with computing x_start which will be x_start = [3 : combinations 0 [4]]

This is not true, because x_start and others are of type [[a1]] . So it's more likely that x_start = [3] : rest , where rest is coming (since list comprehension here is just a syntax sugar with List Monad <- usage) from the combinations 0 [4] . Because of definition combinations 0 [4] is a [[]] , thus there is only one value came from it - [] . Finally, [3] : [] is [[3]] .

As it mentioned in the comments, [3 : [[]]] expression could not be typed by ghci well, because first element is Num a and second element is list of lists, not lists of Num s. This is what compiler is trying to say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM